2016-05-04 9 views
3

私はクエリ(MS SQL Server)に問題があり、以下のようなことができるかどうか、またそれを正しく行う方法があるかどうかを知りたい。結果のない行を表示する(groupby - count)

これはクエリです:

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として0と "サイト" がありませんので

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

質問したいのは、次のように結果を表示する方法はありますか?

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

ありがとうございました!

+1

あなたが「0」で外部結合と置き換えるNULL結果を使用することができます。 – ali

+0

これらの番号範囲は頻繁に使用しますか?次に、テキスト(「4T以上」など)、範囲(例:from = 5、to = null)とソートキー(例:5)を含むテーブルを用意します。これにより、そのようなクエリが簡素化されます。 –

答えて

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 
+0

ありがとう、これは本当にトリックでした! – alecam

3

これは非常に単純です:すべての「数字」を選択し、外側のクエリに参加:

select numbers.str, results.numSites 
from 
(
    select '0T' as str union all 
    select '1T' union all 
    select '2T' union all 
    select '3T' union all 
    select '4T' union all 
    select 'More than 4T' 
) numbers 
left join 
(
    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 
) results on results.numTenants = numbers.str 
order by numbers.str; 
+0

ありがとうございました! – alecam

関連する問題