如何在将 SUM() 用于另一个日期的子句中按日期使用 MIN()?
How to use MIN() by date in a clause that uses SUM() for another date?
我需要找到所有在 2017 年有第一笔订单的客户并汇总他们在 2018 年的收入。我在 SQL 条款中尝试这样做时遇到问题。
在我的 table 中,我有 3 个客户,其中 2 个在 2017-05-23 首次订购,1 个在 2016-06-23 首次订购。所以我想过滤掉那个在 2016 年订购的客户。在 table 中,我有字段:客户、收入、order_date。
这是我在 MySQL:
select client as 'Clients first order in 2017',
SUM(income) as 'Sum of income in 2018'
from orders
where YEAR(order_date) = 2018
and (select client, order_date
from orders
group by client
having min(year(order_date)) = 2017)
order by client
我希望能把2017年第一次下单的所有客户都汇总起来,总结一下他们2018年的收入
使用条件聚合:
Select client as 'Clients first order in 2017',
SUM(CASE WHEN YEAR(order_date) = 2018
THEN income
ELSE 0
END) as 'Sum income in 2018'
FROM orders
GROUP BY client
HAVING MIN (YEAR(order_date)) = 2017
order by client
试试这个-
SELECT
client as 'Clients first order in 2017',
SUM(income) as 'Sum of income in 2018'
FROM orders
WHERE client IN
(
SELECT client
FROM orders
GROUP BY client
HAVING MIN(YEAR(order_date)) = 2017
)
AND YEAR(order_date) = 2018
GROUP BY client
我需要找到所有在 2017 年有第一笔订单的客户并汇总他们在 2018 年的收入。我在 SQL 条款中尝试这样做时遇到问题。
在我的 table 中,我有 3 个客户,其中 2 个在 2017-05-23 首次订购,1 个在 2016-06-23 首次订购。所以我想过滤掉那个在 2016 年订购的客户。在 table 中,我有字段:客户、收入、order_date。
这是我在 MySQL:
select client as 'Clients first order in 2017',
SUM(income) as 'Sum of income in 2018'
from orders
where YEAR(order_date) = 2018
and (select client, order_date
from orders
group by client
having min(year(order_date)) = 2017)
order by client
我希望能把2017年第一次下单的所有客户都汇总起来,总结一下他们2018年的收入
使用条件聚合:
Select client as 'Clients first order in 2017',
SUM(CASE WHEN YEAR(order_date) = 2018
THEN income
ELSE 0
END) as 'Sum income in 2018'
FROM orders
GROUP BY client
HAVING MIN (YEAR(order_date)) = 2017
order by client
试试这个-
SELECT
client as 'Clients first order in 2017',
SUM(income) as 'Sum of income in 2018'
FROM orders
WHERE client IN
(
SELECT client
FROM orders
GROUP BY client
HAVING MIN(YEAR(order_date)) = 2017
)
AND YEAR(order_date) = 2018
GROUP BY client