我遇到以下 sql 代码问题: 我想打印这两年(2019 年和 2020 年)的计数。 现在我只打印 2020。你有一些想法或者可以帮助我处理这个 sql 吗?
SELECT COUNT(u.id) AS total, m.displayMonth
FROM (
SELECT 'Jan' as displayMonth, '01' AS MONTH
UNION SELECT 'Feb' as displayMonth, '02' AS MONTH
UNION SELECT 'Mar' as displayMonth,'03' AS MONTH
UNION SELECT 'Apr' as displayMonth,'04' AS MONTH
UNION SELECT 'May' as displayMonth,'05' AS MONTH
UNION SELECT 'Jun' as displayMonth,'06' AS MONTH
UNION SELECT 'Jul' as displayMonth,'07' AS MONTH
UNION SELECT 'Aug' as displayMonth,'08' AS MONTH
UNION SELECT 'Sep' as displayMonth,'09' AS MONTH
UNION SELECT 'Okt' as displayMonth,'10' AS MONTH
UNION SELECT 'Nov' as displayMonth,'11' AS MONTH
UNION SELECT 'Dec' as displayMonth,'12' AS MONTH
) AS m
LEFT JOIN wpiy_veosoft_crm_customer u
ON MONTH(STR_TO_DATE(CONCAT(m.month, ' 2020'),'%m %Y')) = MONTH(u.date)
AND YEAR(u.date) = '2020'
GROUP BY m.month
下面的 SQL 代码打印出这个:
total DisplayMonth
7 Jan
0 Feb
0 Mar
0 Apr
0 May
0 Jun
0 Jul
0 Aug
0 Sep
0 Okt
0 Nov
0 Dec
我想打印 2020 年和 2019 年的数据。因此以下打印内容如下所示:
2019 2020 DisplayMonth
5 7 Jan
2 0 Feb
1 0 Mar
0 0 Apr
0 0 May
0 0 Jun
0 0 Jul
2 0 Aug
1 0 Sep
0 0 Okt
4 0 Nov
1 0 Dec
最佳答案
您可以使用条件聚合:
SELECT m.displayMonth,
SUM(CASE WHEN YEAR(u.date) = 2019 THEN 1 ELSE 0 END ) as total_2019,
SUM(CASE WHEN YEAR(u.date) = 2020 THEN 1 ELSE 0 END ) as total_2020
FROM (SELECT 'Jan' as displayMonth, '01' AS MONTH UNION ALL
SELECT 'Feb' as displayMonth, '02' AS MONTH UNION ALL
SELECT 'Mar' as displayMonth, '03' AS MONTH UNION ALL
SELECT 'Apr' as displayMonth, '04' AS MONTH UNION ALL
SELECT 'May' as displayMonth, '05' AS MONTH UNION ALL
SELECT 'Jun' as displayMonth, '06' AS MONTH UNION ALL
SELECT 'Jul' as displayMonth, '07' AS MONTH UNION ALL
SELECT 'Aug' as displayMonth, '08' AS MONTH UNION ALL
SELECT 'Sep' as displayMonth, '09' AS MONTH UNION ALL
SELECT 'Okt' as displayMonth, '10' AS MONTH UNION ALL
SELECT 'Nov' as displayMonth, '11' AS MONTH UNION ALL
SELECT 'Dec' as displayMonth, '12' AS MONTH
) m LEFT JOIN
wpiy_veosoft_crm_customer u
ON MONTH(u.date) = m.month AND -- implicit conversion here
YEAR(u.date) IN (2019, 2020)
GROUP BY m.month, m.displayMonth
ORDER BY m.month;
注意查询的更改:
- 使用
UNION ALL
而不是UNION
。没有理由产生删除重复项的开销。 - 日期比较仅使用日期部分。
关于mysql - SQL - 选择两年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59565176/