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 server 计数查询的结果计数-SQL Server_Sql Server - Fatal编程技术网

Sql server 计数查询的结果计数-SQL Server

Sql server 计数查询的结果计数-SQL Server,sql-server,Sql Server,我需要计算计数查询的结果。我的任务是计算通过=0的违规检查的数量,然后将结果分为4类:1违规检查、2违规检查、3或更多违规检查。这需要一个联合是的,但我只想先运行4个查询。这是我到目前为止所拥有的 Select Count(I.ID),I.PermitID,I.Permit# From InspectionItems I Where I.PermitID in (Select SI.PermitID,Count(SI.ID) From InspectionItems SI Where

我需要计算计数查询的结果。我的任务是计算通过=0的违规检查的数量,然后将结果分为4类:1违规检查、2违规检查、3或更多违规检查。这需要一个联合是的,但我只想先运行4个查询。这是我到目前为止所拥有的

Select Count(I.ID),I.PermitID,I.Permit#
From InspectionItems I
Where I.PermitID in
   (Select SI.PermitID,Count(SI.ID) From InspectionItems SI
   Where SI.Passed <> 1
   And SI.Deleted <> 1
   Group By SI.PermitID
   Having Count(SI.ID) = 1)

Group By I.PermitID,I.Permit#
Order By I.PermitID,I.Permit#
ID-主键 PermitID-Forigen键 许可证-用户轻率地贴标签 我得到这个错误

选择时,只能在选择列表中指定一个表达式 子查询不随EXISTS一起引入


从子查询的选择列表中删除计数。您只需要在HAVING子句中使用它:

Select Count(I.ID),I.PermitID,I.Permit#
From InspectionItems I
Where I.PermitID in
   (Select SI.PermitID
 From InspectionItems SI
   Where SI.Passed <> 1
   And SI.Deleted <> 1
   Group By SI.PermitID
   Having Count(SI.ID) = 1)

Group By I.PermitID,I.Permit#
Order By I.PermitID,I.Permit#

您的子查询同时返回PermitID和Count,这就是您得到错误的原因。它需要返回一列值才能用作in的一部分,或者返回一个用于=、!=、的值,等等


可能最简单的方法是先对违规行为进行计数,然后将其放入临时表中,然后从该表中进行计数

另一种可能的方法是使用CTE:

;WITH SI AS (
   Select SI.PermitID
   From InspectionItems SI
   Where SI.Passed <> 1
      And SI.Deleted <> 1
   Group By SI.PermitID
   Having Count(SI.ID) = 1
)

Select Count(I.ID), I.PermitID, I.Permit#
From InspectionItems I
INNER JOIN SI
   ON I.PermitID = SI.PermitID
Group By I.PermitID,I.Permit#
Order By I.PermitID,I.Permit#
您可以一次完成所有查询,而不使用UNION

;WITH SI AS (
   Select SI.PermitID, Count(SI.ID) CountID
   From InspectionItems SI
   Where SI.Passed <> 1
      And SI.Deleted <> 1
   Group By SI.PermitID
)

Select Count(I.ID), I.PermitID, I.Permit#, SI.CountID
From InspectionItems I
INNER JOIN SI
   ON I.PermitID = SI.PermitID
Group By I.PermitID,I.Permit#
Order By I.PermitID,I.Permit#

使用Tab Alleman advice,我得到了要运行的查询,但问题是,我还试图从InspectionItems表中计数,并且这些数字没有聚合。所以我使用了主检查表,它似乎已经分叉了

Select Count(I.InspectionID)
From Inspections I
Where I.PermitID in
   (Select SI.PermitID
   From InspectionItems SI
   Where SI.Passed <> 1
   And SI.Deleted <> 1
   Group By SI.PermitID
   Having Count(SI.ID) = 1)
谢谢你的帮助