SQL查询带来一个列中不存在的月份

问题描述 投票:0回答:2

我想计算相对于它们在数据库中写入的月份的行数。我的数据库有一个名为created_date的列。你可以看到我在下面做了什么:

select month(created_date) as "Month", count(created_date) as "Count" from transactions group by month(created_date)

此查询返回的内容是这样的:

{'Month':1,'Count':10}

之所以这样,是因为我的数据库中只有一个月,而我需要的结果是所有月,包括数据库中不存在的月,就像这样:

{'Month':1,'Count':10}
{'Month':2,'Count':0}
{'Month':3,'Count':0}
{'Month':4,'Count':0}
{'Month':5,'Count':0}
{'Month':6,'Count':0}
{'Month':7,'Count':0}
{'Month':8,'Count':0}
{'Month':9,'Count':0}
{'Month':10,'Count':0}
{'Month':11,'Count':0}
{'Month':12,'Count':0}

我应该怎么做?

mysql sql database
2个回答
0
投票

您可以JOIN到几个月的列表,这样即使表中不存在的月份也可以得到一行:

SELECT m.month,
       COUNT(t.created_date)
FROM (SELECT 1 AS month UNION ALL SELECT 2 UNION ALL SELECT 3
      UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
      UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
      UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) m
LEFT JOIN transactions t ON MONTH(t.created_date) = m.month
GROUP BY m.month

0
投票
SELECT * from
(
 SELECT 1 as month UNION ALL
 SELECT 2 as month UNION ALL
..
SELECT 12 as month 
) as months
left outer join
(
select month(created_date) as "Month", count(created_date) as "Count" from transactions group by month(created_date)
) as data
on (months.month=data.month)
ORDER BY months.month
© www.soinside.com 2019 - 2024. All rights reserved.