这是我的“客户”表:
要获取特定月份和年份中每个查询的数量,我使用以下查询:
SELECT YEAR(customer_date) AS Year, MONTH(customer_date) AS Month, COUNT(customer_id) AS Count FROM customers WHERE customer_product = 6 GROUP BY YEAR(customer_date), MONTH(customer_date)
我得到以下结果:
您可以看到,由于四月份没有查询,因此没有为月份4提取任何行。但是,如果在那个特定的月份和年份中没有找到记录,我希望Count列中的值为0。
这就是我想要的:
答案 0 :(得分:0)
一个选项使用日历表来表示所有月份和年份,即使那些未出现在数据集中的月份和年份:
SELECT
t1.year,
t2.month,
COUNT(c.customer_id) AS Count
FROM
(
SELECT 2017 AS year UNION ALL
SELECT 2018
) t1
CROSS JOIN
(
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
) t2
LEFT JOIN customers c
ON t1.year = YEAR(c.customer_date) AND
t2.month = MONTH(c.customer_date)
WHERE
c.customer_product = 6
GROUP BY
t1.year,
t2.month
ORDER BY
t1.year,
t2.month;
注意:通过在MySQL模式中实际创建专用日历表,可以使上述查询更快。
在customers
表上的以下索引可能会有所帮助:
CREATE INDEX idx ON customers(customer_product, customer_id);
假设customers
条件是限制性的,这可能会使日历表和customer_product = 6
之间的连接更快。