Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
资产清单数据库的SQL计数查询_Sql_Sql Server - Fatal编程技术网

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

资产清单数据库的SQL计数查询,sql,sql-server,Sql,Sql Server,我目前正在制作一个简单的库存资产跟踪数据库。我想有一个审计功能,它将统计一个立方体(隔间)中台式机、显示器和电话的数量。我对SQL不太了解,这是我第一个使用MSSQL的项目。数据库是一个表,到目前为止没有关系。我有一个名为devicetype的列,它存储桌面、显示器、电话等。我需要一种方法来计算多维数据集的每种设备类型。我的主键是资产标签。我的思维过程是这样的: select Count(monitor,phone,desktop per cube) from table having coun

我目前正在制作一个简单的库存资产跟踪数据库。我想有一个审计功能,它将统计一个立方体(隔间)中台式机、显示器和电话的数量。我对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个监视器资产。我希望查询告诉我所有不遵循这些规则的多维数据集,以便我们可以手动检查它们。我不确定我的数据库是否正确设置来执行此操作,而且我对查询的了解不够,无法实现这一点。任何帮助、想法或问题都会令人惊讶。谢谢

我想你想要:

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],
作为num_监视器的sum(当devicetype='monitor'然后为1,否则为0结束时的情况),
总和(当devicetype='phone'然后为1或0结束时的情况)为num_phones,
总和(当devicetype='desktop'时为1,否则为0结束)作为num_桌面
从样本数据
分组依据[多维数据集]
具有总和(当devicetype='monitor'然后为1或0 end时的情况)1或
总和(当devicetype='phone'然后是1 else 0 end时的情况)1或
总和(当devicetype='desktop'时为1,否则为0结束)2;

cube
对于列来说是一个糟糕的名称,因为它是SQL Server保留字。这意味着它需要转义。

谢谢你,戈登!这很有效,我没有意识到这是一个保留字。我最终不得不+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;

请提供样本数据和期望结果。更新样本数据和期望结果。感谢快速回复!当我为多维数据集添加where语句时,这非常有效。但是我如何让它在所有的立方体中循环呢。另外,你能解释一下
then 1 else 0 end
part吗?这给了我一个语法错误:“having”附近的语法不正确。应为“(”。然后在包含部分后显示无效列名。