开发者社区 问答 正文

资产清单数据库的SQL计数查询

我目前正在建立一个用于简单库存资产跟踪的数据库。我想拥有一个审计功能,该功能将计算一个立方体(cubicle)中的台式机,显示器和电话的数量。我对SQL并不了解很多,这是我第一个使用MSSQL的项目。该数据库是一个表,到目前为止还没有任何关系。我有一列称为devicetype的列,其中存储了DESKTOP,MONITOR,PHONE,ETC。我需要一种方法来为多维数据集计算每种设备类型。我的主键是资产标签。我的思考过程是这样的:

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

展开
收起
祖安文状元 2020-01-05 14:35:35 485 分享
分享
版权
举报
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 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保留字。那意味着它需要被逃脱。

    2020-01-05 14:35:45 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等