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

时间:2019-11-08 11:46:43

标签: mysql sql database

我想计算相对于它们在数据库中写入的月份的行数。我的数据库有一个名为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}

我应该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以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

答案 1 :(得分:1)

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