sql - 资产库存数据库的 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 个监视器资产。我希望查询告诉我所有不遵循这些规则的多维数据集,以便我们可以手动检查它们。我不确定我的数据库是否设置正确以执行此操作,并且我对查询的了解不足以实现此目的。任何帮助、想法或问题都会令人惊叹。谢谢
解决方案
我想你想要:
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 保留字。这意味着它需要被转义。
推荐阅读
- python - 如何使用 Selenium 和 Python 在 https://tengrnews.kz 中提取 7 个主要新闻的时间和标题
- reactjs - 什么是 React Native Web?
- javascript - 如何在客户端排除导入
- python - 分配 django 之前引用的局部变量“用户名”
- apache-kafka - 卡夫卡连接 - 文件源
- typescript - 在堆叠类Angular 9 TypeScript中对列名进行排序
- django - 具有不同用户名字段类型的两种不同类型的用户
- batch-file - 使用批处理文件对 exe 进行基准测试
- linux - 如何在 linux 中从后台取消设置环境变量?
- typescript - 打字稿应该每个输入参数都是一个带有接口的对象,即使很简单?