使用GROUP BY在SQL Server中创建视图
我需要在SQL Server中构建一个视图,该视图将从此表中获取数据:使用GROUP BY在SQL Server中创建视图,sql,sql-server,tsql,Sql,Sql Server,Tsql,我需要在SQL Server中构建一个视图,该视图将从此表中获取数据: pc_name template powerstate domain -------------------------------------- pc1 true poweredON domain1 pc2 true poweredOFF domain2 pc3 false poweredON domain1 pc4 false powere
pc_name template powerstate domain
--------------------------------------
pc1 true poweredON domain1
pc2 true poweredOFF domain2
pc3 false poweredON domain1
pc4 false poweredOFF domain2
pc5 true poweredON domain1
pc6 true poweredOFF domain2
...
选择列“Template”为“False”的所有计算机,按域将它们分开,并计算打开/关闭的计算机数量和总数,类似于这样:
powerstateON powerstateOFF Total
----------------------------------------------
domain1 100 50 150
domain2 30 5 35
Grand total 130 55 185
我对T-SQL的了解非常有限,我知道我必须使用selects和group by,并花了几个小时把一些东西放在一起,但它甚至不接近,不知道如何正确地做到这一点…您可以使用条件聚合和
分组集
:
select coalesce(domain, 'Total'),
sum(case when powerstate = 'PowerON' then 1 else 0 end) as poweron,
sum(case when powerstate = 'PowerOFF' then 1 else 0 end) as poweroff,
count(*) as total
from t
where template = 'false'
group by grouping sets ( (domain), () )
您可以执行条件聚合:
select coalesce(domain, 'Grand Total'),
sum(case when powerstatus = 'on' then 1 else 0 end) as poweron,
sum(case when powerstatus = 'off' then 1 else 0 end) as poweroff,
count(*) as total
from table t
where t.template = 0 -- assuming bit type
group by domain with rollup;
谢谢,这个很好用。有趣的是,你们和@Yogesh Sharma在30秒之间得到了几乎相同的答案,但你们是第一个,所以我将其标记为答案。再次感谢。我会努力理解和学习的。谢谢你,这很好用。我感谢你的帮助!