我已经查询了本周检索每日数据的信息。我希望得到如下表格:
hari total finish issue
------ ------ ------ --------
1 0 0 0
2 0 0 0
3 1 0 1
4 1 1 0
5 0 0 0
6 0 0 0
7 0 0 0
这是我的疑问:
SELECT DAYOFWEEK(`waktu`) AS hari,
COALESCE( (COUNT(*) ), 0) AS total,
COUNT(IF(`jarak`<70,1,NULL)) AS finish,
COUNT(IF(`jarak`>70,1,NULL)) AS issue
FROM `presensi`
WHERE WEEKOFYEAR(`waktu`)=WEEKOFYEAR(NOW())
GROUP BY hari;
但是,查询不显示零结果。如何用emty数据显示一周中的所有日子,包括白天?
答案 0 :(得分:0)
一周只有7天,所以这对left join
很容易:
SELECT dow.dow AS hari,
COUNT(p.waktu) AS total,
SUM(`jarak` < 70) AS finish,
SUM(jarak > 70) AS issue
FROM (select 0 as dow union all select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6
) dow left join
`presensi` p
on p.DAYOFWEEK(`waktu`) = dow.dow and
WEEKOFYEAR(`waktu`) = WEEKOFYEAR(NOW())
GROUP BY dow.dow;
答案 1 :(得分:0)
我已经解决了我的问题。我创建了一个带有日期列表的虚拟表(来自@ drew-pierce的想法)。 我的查询:
SELECT
h.`id`,
COALESCE(d.total,0) AS total,
COALESCE(d.finish,0) AS finish,
COALESCE(d.issue,0) AS issue
FROM
hari_dummy h
LEFT JOIN
(
SELECT
DAYOFWEEK(p.waktu) AS hari,
COUNT(p.waktu) AS total,
COUNT(IF(p.`jarak` < 70, 1, NULL)) AS finish,
COUNT(IF(p.`jarak` > 70, 1, NULL)) AS issue
FROM
`presensi` p
WHERE
WEEKOFYEAR(waktu) = WEEKOFYEAR(NOW())
GROUP BY hari
) d
ON d.hari = h.`id`
ORDER BY h.id ASC;