我有SQL命令:
SELECT
vinculo.id,
data start,
count(*) title
from
atendimento_regulacao
join vinculo on vinculo.id = atendimento_regulacao.vinculo_id
where data = '2019-07-02'
group by vinculo.usuario_id, atendimento_regulacao.data
结果为空,因为where data = '2019-07-02'
上不存在任何记录
如何显示如下所示的id
?
id | start | title
1 | |
答案 0 :(得分:1)
您可以使用CROSS JOIN
生成行,并使用LEFT JOIN
引入结果:
select v.id, d.dte as start, count(ar.vinculo_id) as num_title
from (select '2019-07-02' as dte) d cross join
vinculo v left join
atendimento_regulacao ar
on v.id = ar.vinculo_id and ar.data = d.dte
group by v.id, d.dte;
如果您确实要按v.usuario_id
进行汇总,则将其同时包含在select
和group by
中。
注意:
GROUP BY
在SELECT
中使用相同的列。COUNT()
使用ar
中的一列,因此它可以返回0
。对于单个日期的特定情况,您可以使用条件汇总:
select v.id, '2019-07-02' as start,
count(ar.vinculo_id) as num_title
from vinculo v left join
atendimento_regulacao ar
on v.id = ar.vinculo_id and ar.data = '2019-07-02'
group by v.id;
答案 1 :(得分:1)
使用RIGHT JOIN
,并将您的count
转换为下面的数字,否则,只要没有发现任何计数,它就会显示为零。
SELECT v.id, a.data start,
case when count(*) is null then null end title
FROM atendimento_regulacao a
RIGHT JOIN vinculo v
ON v.id = a.vinculo_id
AND a.data = '2019-07-02'
GROUP BY v.usuario_id, a.data;