根据@gordon的评论进行编辑---
假设以下情况
CREATE TABLE card (date_field, numcard, month);
INSERT INTO card (date_filed, numcard, month)
VALUES
(2018-06-01, 12531, June-2018),
(2018-06-02, 29182, June-2018),
(2018-05-01, 12781, May-2018),
(2018-05-29, 56171, May-2018),
(2018-05-10, 27191, May-2108),
(2018-04-10, 83231, April-2018),
(2018-03-01, 31131, March-2018),
(2018-03-02, 47131, March-2018),
(2018-02-15, 34617, February-2018);
在这种情况下,我试图使用一个查询获取2018年6月(M),2018年5月(M-1)和2018年3月(M-3)的卡号...以及输出应该是这样的1X3矩阵... Desired Output
我尝试使用以下查询解决该问题:
为了解决我的问题,我遇到了这个讨论 MySQL Query to calculate the Previous Month和这一个: MySQL: Select previous month and month before
SELECT count(*) as 'M', '' as'M-1', '' as 'M-3' FROM my_table WHERE YEAR(date_field) = YEAR(CURRENT_DATE - INTERVAL 2 MONTH) AND MONTH(date_field) = MONTH(CURRENT_DATE - INTERVAL 2 MONTH)
UNION
SELECT '' as 'M', count(*) as'M-1', '' as 'M-3' FROM my_table WHERE YEAR(date_field) = YEAR(CURRENT_DATE - INTERVAL 3 MONTH) AND MONTH(date_field) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH)
UNION
SELECT '' as 'M', '' as 'M-1', count(*) as 'M-3' FROM my_table WHERE YEAR(date_field) = YEAR(CURRENT_DATE - INTERVAL 4 MONTH) AND MONTH(date_field) = MONTH(CURRENT_DATE - INTERVAL 4 MONTH)
...它给出一个
仅带有对角线的值(位:-( ...)。
我想要的是这个
。
***谢谢您的帮助和见解。 周末快乐!
答案 0 :(得分:2)
您可以使用条件聚合。只计算满足条件的行。如果满足条件,请使用CASE
来返回任何非null值。否则,CASE
默认情况下将返回null,并且如果count(ex)
的值为ex
,则NULL
不计算行,则不计算行。
您可能还想以某种方式重做条件,即date_field
是比较运算符一侧的完整表达式,因此可以使用date_field
上的索引。 (对于WHEN
中的表达式不是那么重要,但对于WHERE
子句中的表达式来说并不重要。)
SELECT count(CASE
WHEN date_field >= current_date - interval 2 month - interval dayofmonth(current_date) - 1 day
AND date_field < current_date - interval 1 month - interval dayofmonth(current_date) - 1 day THEN
1
END) `M`,
count(CASE
WHEN date_field >= current_date - interval 3 month - interval dayofmonth(current_date) - 1 day
AND date_field < current_date - interval 2 month - interval dayofmonth(current_date) - 1 day THEN
1
END) `M-1`,
count(CASE
WHEN date_field >= current_date - interval 4 month - interval dayofmonth(current_date) - 1 day
AND date_field < current_date - interval 3 month - interval dayofmonth(current_date) - 1 day THEN
1
END) `M-3`,
FROM my_table
WHERE date_field >= current_date - interval 4 month - interval dayofmonth(current_date) - 1 day
AND date_field < current_date - interval 1 month - interval dayofmonth(current_date) - 1 day;
答案 1 :(得分:0)
几乎可以肯定,有一种更好的方法可以做您想做的事情,但是鉴于您所拥有的,您可以做这样的事情:
select max(a), max(b), max(c) from(
select '1' as a, ''as b, '' as c
union
select '' as a, '2' as b, '' as c
union
select '' as a, '' as b, '3' as c
) d;