在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
答案 0 :(得分: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
答案 1 :(得分: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