0

SQL Server で特定の列をカウントするクエリを作成しましたが、すべてのカウントを複数のテーブルに表示しています。これは表示するのに適した方法ではありません。すべてのテーブルを新しいテーブルの単一行に表示する方法は?

     select COUNT(s.AssetSubType) as 'PhysicalServers' from Asset s
      where s.CompanyId = @companyId and
            s.AssetType = 1 and
            s.AssetSubType = 4 

   select COUNT(s.AssetSubType) as 'WorkStations' from Asset s
      where s.CompanyId = @companyId and
            s.AssetType = 1 and
            s.AssetSubType = 1 or s.AssetSubType = 3    

 select COUNT(s.AssetSubType) as 'EmailOnlyUsers' from Asset s
      where s.CompanyId = @companyId and
            s.AssetType = 2 and 
            s.AssetSubType = 16             

 select COUNT(s.OperatingSystem) as '#OfMSServers' from Asset s
      where s.CompanyId = @companyId and
            s.AssetType = 1 and
            s.AssetSubType = 4 and 
            s.OperatingSystem = 1 

 select COUNT(s.OperatingSystem) as '#OfLinuxServers' from Asset s
      where s.CompanyId = @companyId and
            s.AssetType = 1 and
            s.AssetSubType = 4 and 
            s.OperatingSystem = 2   
4

2 に答える 2

2

このようなものはあなたのために働くはずです

select sum(case when s.AssetType = 1 and 
                     s.AssetSubType = 4 
                then 1 end) as 'PhysicalServers',
       sum(case when s.AssetType = 1 and 
                     (s.AssetSubType = 1 or s.AssetSubType = 3) 
                then 1 end) as 'WorkStations',
       sum(case when s.AssetType = 2 and 
                     s.AssetSubType = 16 
                then 1 end) as 'EmailOnlyUsers',
       sum(case when s.AssetType = 1 and 
                     s.AssetSubType = 4 and 
                     s.OperatingSystem = 1 
                then 1 end) as '#OfMSServers',
       sum(case when s.AssetType = 1 and 
                     s.AssetSubType = 4 and 
                     s.OperatingSystem = 2 
                then 1 end) as '#OfLinuxServers'
from Asset s
where s.CompanyId = @companyId
于 2012-05-24T11:58:44.027 に答える
0

構成タイプごとに一意の値を持つ計算列「serverType」を作成できます。

ALTER TABLE [Asset]
 ADD [serverType] AS (
    CASE 
     WHEN (AssetType = 1 and AssetSubType = 4) THEN 'PhysicalServers'
     WHEN (AssetType = 1 and AssetSubType = 1 AssetSubType = 3) THEN 'WorkStations'
     [etc..]
     ELSE 'Unknown'
    END
) 

次に、単にクエリを実行できます

SELECT COUNT(s.OperatingSystem) FROM Asset s
WHERE s.CompanyId = @companyId 
GROUP BY serverType
于 2012-05-24T11:58:37.377 に答える