[英]MYSQL Group by both subqueries without repeating rows
How do I avoid repeating results in the following query? 如何避免在以下查询中重复结果?
Example table structure: 表结构示例:
ord_order_number | ord_date | ord_status | ord_from
----------------------------------------------------
1 | 2017-01-01 | 2 | Admin Side
2 | 2017-02-02 | 3 | Client Side
There would be orders from all months leading up to 5 (Current month, May) 从所有月份开始的订单最多到5(本月,5月)
Here is the query: 这是查询:
SELECT t1.*, t2.*
from
(select count(ord_order_number) as admin, ord_date
FROM `order_summary`
where ord_date > '2017-01-01 00:00:00'
and ord_from = 'Admin Side'
group by month(ord_date)
) t1,
(select count(ord_order_number) as client, ord_date
FROM `order_summary`
where ord_date > '2017-01-01 00:00:00'
and ord_from = 'Client Side'
group by month(ord_date)
)t2
This will currently produce 25 4 columned rows. 当前将产生25 4列的行。
The T1 alias will produce a count of each month starting from 2017-01 and ending and 2017-05. T1别名将产生从2017-01到2017-05的每个月的计数。 Each row would then repeat itself starting at 2017-01 etc... 然后每行将从2017年1月开始重复自身,以此类推...
while the t2 alias will repeat each month 5 times. 而t2别名将每月重复5次。
I would like for each month to only appear once. 我希望每个月只出现一次。
Example results of current query: 当前查询的示例结果:
(correct)admin | ord_date | client | ord_date (this column repeats each date 5 times)
--------------------------------------------
22 | 2017-01-01 | 77 | 2017-01-01
32 | 2017-02-01 | 77 | 2017-01-01
43 | 2017-03-01 | 77 | 2017-01-01
Here's an example of the expected results 这是预期结果的一个例子
admin | ord_date | client | ord_date
--------------------------------------------
22 | 2017-01-01 | 77 | 2017-01-01
32 | 2017-02-01 | 21 | 2017-02-01
43 | 2017-03-01 | 100 | 2017-03-01
Move the condition in the select with CASE.You can add the ord_date again in the select but it looks weird to me. 使用CASE移动选择中的条件。您可以在选择中再次添加ord_date,但它对我来说很奇怪。
SELECT count(CASE WHEN ord_from = 'Admin Side' THEN ord_order_number END) as admin
, count(CASE WHEN ord_from = 'Client Side' THEN ord_order_number END) as client
, ord_date
FROM `order_summary`
WHERE ord_date > '2017-01-01 00:00:00'
GROUP BY month(ord_date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.