MSSQL按嵌套值分组

时间:2018-12-19 11:41:21

标签: sql-server tsql

我需要按一系列嵌套关系进行分组。使用以下示例。假设每个人的姓名对于数据库都是唯一的。

Person | Sibling 1 | Sibling 2
-------+-----------+-----------
Jason  | Brad      | Sheri
Brad   | Sheri     | Jason
Sheri  | Brad      | Tina
Tina   | Sheri     | Sam
Sam    | Kara      | Tina
Kara   | Sam       | Tina
James  | Kelly     | NULL
Kelly  | James     | NULL
Fred   | NULL      | NULL

如何编写查询以获取此结果?

Person | Family
-------+--------
Jason  | 1
Brad   | 1
Sheri  | 1
Tina   | 1
Sam    | 1
Kara   | 1
James  | 2
Kelly  | 2
Fred   | 3

理想情况下,无需使用CLR或CTE等外部代码。

编辑:以下输出也是可接受的。

Family | Siblings
-------+-------------------------------------
1      | Jason, Brad, Sheri, Tina, Sam, Kara
2      | James, Kelly
3      | Fred

1 个答案:

答案 0 :(得分:0)

以下是我对您的问题的解答(使用CTE):

declare @tb table (Person varchar(10), Sibling1 varchar(10), Sibling2 varchar(10))
insert into @tb values
('Jason','Brad', 'Sheri'), ('Brad', 'Sheri','Jason'), ('Sheri','Brad', 'Tina'),
('Tina', 'Sheri','Sam'),   ('Sam',  'Kara', 'Tina'),  ('Kara', 'Sam',  'Tina'),
('James','Kelly',NULL),    ('Kelly','James',NULL),    ('Fred', NULL,   NULL)

with b
as (select
     Person
    ,Related = (select COUNT(*) from @tb where a.Person in (Sibling1, Sibling2))
    from @tb a
    )
select c.Person, Family = 
    case (select SUM(b.Related) from b where b.Person in (c.Person, c.Sibling1, c.Sibling2))
        when 0 then 3
        when 2 then 2
        else 1
    end
from @tb c