Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.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 我需要使用Over()子句将单个列中的两个计数值放在同一行中_Sql_Tsql - Fatal编程技术网

Sql 我需要使用Over()子句将单个列中的两个计数值放在同一行中

Sql 我需要使用Over()子句将单个列中的两个计数值放在同一行中,sql,tsql,Sql,Tsql,我从Select语句中得到以下结果 UnitId UnitType GroupId 1 1 1 2 1 1 3 1 2 4 2 2 5 2 2 6 2 2 7 2 2 我需要每个组Id的以下结果 GroupId Cou

我从Select语句中得到以下结果

UnitId     UnitType  GroupId
 1          1          1
 2          1          1
 3          1          2
 4          2          2
 5          2          2
 6          2          2
 7          2          2  
我需要每个组Id的以下结果

GroupId CountBasedOnUnitType1 CountBasedOnUnitType2
   1           2                      0
   2           1                      4

提前感谢。

是否一定需要将<代码>置于之上

select 
  GroupID, 
  sum(case when UnitType = 1 then 1 else 0 end) CountBasedOnUnitType1, 
  sum(case when UnitType = 2 then 1 else 0 end) CountBasedOnUnitType2
from table
group by GroupID
试试这个

SELECT * FROM
(
  SELECT GroupId,
    UnitType
  FROM Table1
) x
Pivot
(
  Count(UnitType)
  For UnitType in ([1], [2])
) p

输出



我将usign OVER子句实现为:选择gu.GroupId,Count(CASE gu.UnitType当1时,则1 ELSE NULL END)OVER(按gu.GroupId分区)作为CountBasedOnUnitType1,Count(CASE gu.UnitType当2时,则2 ELSE NULL END)OVER(按gu.GroupId分区)作为Group_Unit GUI中的CountBasedOnUnitType2,有没有其他不声明列名的方法?如果有一群猎犬,会发生什么?这里可以看到动态使用。
GroupId        1          2
   1           2          0
   2           1          4