显示非结果行SQL(groupby - count)

时间:2016-05-04 08:16:56

标签: sql sql-server

我遇到查询问题(MS SQL Server),我想知道是否可以执行以下操作以及如何正确执行此操作。

这是查询:

select numTenants, count(codSite) numSites
from (select case count(st1.name) when 0 then '0T'
                       when 1 then '1T' 
                       when 2 then '2T' 
                       when 3 then '3T'
                       when 4 then '4T'
                       else 'More than 4T' end numTenants, os1.siteCode as codSite
    from fl_OperativeSite os1 left join fl_SiteTenant st1
        on st1.fkOperativeSite=os1.pkOperativeSite
    where  os1.siteType='A' and os1.externalInfrastructure=2
    group by os1.siteCode) groups
group by numTenants
order by numTenants

这就是结果:

numTenants     numSites
   1T             2957
   2T              553
   3T             1503
   4T              423
More than 4T       131

因为很明显没有一个“网站”,其中0为numTenants。

我想问的是:有没有办法让结果显示如下?

numTenants     numSites
   0T                0
   1T             2957
   2T              553
   3T             1503
   4T              423
More than 4T       131

非常感谢!

2 个答案:

答案 0 :(得分:3)

这很简单:选择所有"数字"和外部加入您的查询:

<html>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

答案 1 :(得分:1)

假设您自己的查询工作正常。 创建一个表变量。

declare @tbl table(numTenants varchar(50))
insert into @tbl values ('0T'), ('1T'),('2T'),('3T'),('4T'),('More than 4T')

;With CTE As
(
 select numTenants, count(codSite) numSites
from (select case count(st1.name) when 0 then '0T'
                       when 1 then '1T' 
                       when 2 then '2T' 
                       when 3 then '3T'
                       when 4 then '4T'
                       else 'More than 4T' end numTenants, os1.siteCode as codSite
    from fl_OperativeSite os1 left join fl_SiteTenant st1
        on st1.fkOperativeSite=os1.pkOperativeSite
    where  os1.siteType='A' and os1.externalInfrastructure=2
    group by os1.siteCode) groups
group by numTenants
order by numTenants
)

select a.numTenants,isnull(s.numSites,0) numSites from @tbl A 
left join CTE S on a.numTenants=s.numTenants