我目前正在制作一个数据库,用于简单的库存资产跟踪。我想有一个审计功能,将计算台式机,显示器和电话在一个立方体(小隔间)的数量。我对SQL知之甚少,这是我使用MSSQL的第一个项目。数据库是一个表,到目前为止还没有关系。我有一个名为devicetype的列,它存储桌面、显示器、电话等。我需要一种方法来计算多维数据集的每个设备类型。我的主键是资产标签。我的想法是这样的:
select Count(monitor,phone,desktop per cube)
from table
having count(devicetype.desktop>1), count(devicetype.phone>1), Count(devicetype.monitor>2).我知道这不是你写的方式,这只是解释我认为应该发生的事情。基本上每个立方体应该只有1个桌面资产,1个电话资产和2个显示器资产。我想让查询告诉我所有不遵循这些规则的立方体,这样我们就可以手动检查它们。我不确定我的数据库是否正确设置来执行此操作,并且我对查询的了解也不足以实现此操作。任何帮助、想法或问题都将令人惊叹。谢谢

发布于 2019-12-19 23:19:31
我认为你想要:
Select [cube],
sum(case when devicetype = 'monitor' then 1 else 0 end) as num_monitors,
sum(case when devicetype = 'phone' then 1 else 0 end) as num_phones,
sum(case when devicetype = 'desktop' then 1 else 0 end) as num_desktops
from sampledata
group by [cube]
having sum(case when devicetype = 'monitor' then 1 else 0 end) <> 1 or
sum(case when devicetype = 'phone' then 1 else 0 end) <> 1 or
sum(case when devicetype = 'desktop' then 1 else 0 end) <> 2;对于列来说,cube不是一个好的名称,因为它是SQL Server保留字。这意味着需要对其进行转义。
发布于 2019-12-20 03:22:08
谢谢,戈登!这工作得很好,我没有意识到这是一个保留字。我最终不得不将这些值加1。它最终是这样的:
Select [cube],
sum(case when devicetype = 'monitor' then 1 else 0 end) as num_monitors,
sum(case when devicetype = 'phone' then 1 else 0 end) as num_phones,
sum(case when devicetype = 'desktop' then 1 else 0 end) as num_desktops
from table
group by [cube]
having sum(case when devicetype = 'monitor' then 1 else 0 end) > 2 or
sum(case when devicetype = 'phone' then 1 else 0 end) > 2 or
sum(case when devicetype = 'desktop' then 1 else 0 end) > 3;https://stackoverflow.com/questions/59412517
复制相似问题