计算成员的类型 table (Self Join/Case When or any other possible way)

Calculate Type of the member in a table (Self Join/Case When or any other possible way)

这是 Table :

If OBJECT_ID ('tempdb..##SelfCount') Is not null
    drop table #SelfCount

create table #SelfCount (CanID int , CanType int)

insert into #SelfCount (CanID, CanType)
values
(1,0),
(2,0),
(1,1),
(2,1),
(1,2),
(1,2),
(1,0)

CanID   CanType     
1             0     
2             0     
1             1     
2             1     
1             2     
1             2     
1             0     

我希望结果是这样的

CanID   Self    Spouse  Dependent
1         2       1         2
2         1       1         0/NULL --It doesn't matter if it's nUll or 0

我写了这个查询

select  CanID, 
        case 
        When CanType = 0 then count(CanType) 
        end as [self],
        case 
        when CanType = 1 then count(CanType)
        end as [Spouse],
        Case 
        When CanType = 2 then count(CanType)
        end as [Dependent]
from #SelfCount
Group by CanID, CanType

但是结果集是这样的:

CanID   Self   Spouse     Dependent
1       2       NULL        NULL
2       1       NULL        NULL
1       NULL    1           NULL
2       NULL    1           NULL
1       NULL    NULL        2

我试过Recursive的方法,如果谁能同时提供Recursive和Set的处理方法,将不胜感激

可能这就是您需要的:

select CanID, 
       sum(case when CanType = 0 then 1 else 0 end) as [Self],
       sum(case when CanType = 1 then 1 else 0 end) as [Spouse],
       sum(case when CanType = 2 then 1 else 0 end) as [Dependent]
from #SelfCount
group by CanID

通过在 group by 子句中包含 CanType,您会为每个 CanType(和 CanId 的不同值获得单独的结果行,因为它也是包含在 group by 子句中)。

相反,您应该在 group by 子句中只包含 CanId,并在 case 表达式上应用不同的 count

SELECT   CanID, 
         COUNT (CASE CanType WHEN 0 THEN 1 END) AS [Self], 
         COUNT (CASE CanType WHEN 1 THEN 1 END) AS [Spouse], 
         COUNT (CASE CanType WHEN 2 THEN 1 END) AS [Dependent], 
FROM     #SelfCount
GROUP BY CanID

您可以尝试 PIVOT:

select 
  CanID, 
  [0] as Self, 
  [1] as Spouse, 
  [2] as Dependent 
from tab
pivot
(
  count (CanType)
  for CanType IN ([0], [1], [2])
) as pvt

基本上,它将根据 PIVOT 子句中未声明的所有列进行分组(实际上,只是 CanID),然后创建三个聚合 COUNT 列,一个 FOR 每个 CanType IN 值列表。如果您需要计算更多的值,只需在 IN 子句和 SELECT 子句中定义它们。