想在group by子句中强制为零

时间:2018-05-09 19:25:49

标签: sql-server

嗨,这是我的简单查询

--Code formatting
select severity as measurement,
       count(tkts) as tkts
from Maintable
where (Bunch of conditions)
group by severity

我得到了正确的结果,但是没有显示结果为0的严重性,我想强制所有严重性,即使它们没有票。

使用SQL Server 2012

1 个答案:

答案 0 :(得分:2)

从所有严重性值开始,并left join主表:

select  sev.severity as measurement
,       count(mt.id) as tkts 
from    (
        values (1), (2), (3), (4), ..., (N)
        ) sev(severity)
left join
        (
        select  *
        from    Maintable 
        where   <bunch of conditions>
        ) mt
on      mt.severity = sev.severity
group by 
        sev.severity

根据您的评论,添加一个层:

select  sev.severity as severity_name
,       tier.tier as tier_name
,       count(mt.id) as tkts 
from    (
        values (1), (2), (3), (4), ..., (N)
        ) sev(severity)
cross join
        (
        values ('A'), ('A2'), ('B'), ..., ('last')
        ) tier(tier)
left join
        (
        select  *
        from    Maintable 
        where   <bunch of conditions>
        ) mt
on      mt.severity = sev.severity
        and mt.iter = tier.tier
group by 
        sev.severity
,       tier.tier