我在mysql数据库中有一些事件及其日期的表格,我想回复每个工作日的事件计数:
SELECT DAYNAME(start_date) AS day, count(DAYNAME(start_date)) as number FROM events GROUP BY day
这适用于发生某些事件的日子,但它没有显示空日。我知道如果我有一个简单的表格,一周中的几天我可以做一个简单的LEFT JOIN并显示所有日期,当日期为空时,计数= 0。但是,如果没有创建该表,有没有更简单的方法呢?还有其他想法吗?
提前致谢
答案 0 :(得分:1)
一句话'不'。原因是您试图选择不存在的数据!
但是,由于一周内只有7天,您可以动态构建简单的“每周工作日”表:
select dayname('2011-10-31') union
select dayname('2011-11-01') union
select dayname('2011-11-02') union
select dayname('2011-11-03') union
select dayname('2011-11-04') union
select dayname('2011-11-05') union
select dayname('2011-11-06');
然后从LEFT OUTER JOIN
进入事件表(正如您所描述的那样)。这将允许您运行查询,而无需创建和填充简单表。
虽然为了重用和整洁,我会用一周中的几天创建并填充简单表格并使用它。
答案 1 :(得分:1)
SELECT
COALESCE(DAYNAME(start_date),'empty') AS day
, count(start_date) as number
FROM events
RIGHT JOIN (SELECT 0 as dy FROM DUAL UNION ALL
SELECT 1 as dy FROM DUAL UNION ALL
SELECT 2 as dy FROM DUAL UNION ALL
SELECT 3 as dy FROM DUAL UNION ALL
SELECT 4 as dy FROM DUAL UNION ALL
SELECT 5 as dy FROM DUAL UNION ALL
SELECT 6 as dy FROM DUAL UNION ALL
SELECT 'empty' as dy FROM DUAL) ds
ON (ds.dy = COALESCE(DAYNAME(start_date),'empty'))
GROUP BY ds.dy