首页 > 解决方案 > 资产库存数据库的 SQL 计数查询

问题描述

我目前正在制作一个用于简单库存资产跟踪的数据库。我想要一个审计功能,它可以计算一个多维数据集(机柜)中的桌面、显示器和电话的数量。我对 SQL 不太了解,这是我第一个使用 MSSQL 的项目。数据库是一张表,目前还没有任何关系。我有一个名为 devicetype 的列,它存储 DESKTOP、MONITOR、PHONE 等。我需要一种方法来计算多维数据集的每种设备类型。我的主键是资产标签。我的思考过程是这样的:

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 个监视器资产。我希望查询告诉我所有不遵循这些规则的多维数据集,以便我们可以手动检查它们。我不确定我的数据库是否设置正确以执行此操作,并且我对查询的了解不足以实现此目的。任何帮助、想法或问题都会令人惊叹。谢谢

在此处输入图像描述

标签: sqlsql-server

解决方案


我想你想要:

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 保留字。这意味着它需要被转义。


推荐阅读