合并分组列的结果

时间:2015-08-13 20:35:56

标签: sql sql-server-2012 union

Consider table A:

Status                Person
------                ------
Married               Andy
Married               Bob
Married               Carol
Has Kids              Bob
Has Kids              Carol

Consider table B:

Married & Has Kids    Bob
Married & Has Kids    Carol

我可以得到表A,我可以得到表B,但是如何一起显示A和B?我是SQL的新手,所以我对UNION有一个模糊的想法,那会是最好的方法吗?

编辑:

所以,我有点撒了谎。我无法准确得到表B,但类似:

Married               Bob
Has Kids              Bob
Married               Carol
Has Kids              Carol

我正在使用SQL Server 2012.这是我对表A的查询:

SELECT Status,Person
FROM Records
WHERE Status IN ('Married', 'Has Kids')
GROUP BY Status,Person
ORDER BY Status,Person

查询表B-ish:

SELECT Status,Person
FROM Records
WHERE Status='Married' AND Status='Has Kids'
GROUP BY Status,Person
ORDER BY Status,Person

想要这样的表:

Status                Person
------                ------
Married               Andy
Married               Bob
Married               Carol
Has Kids              Bob
Has Kids              Carol
Married & Has Kids    Bob
Married & Has Kids    Carol

1 个答案:

答案 0 :(得分:0)

一种方法是使用自联接并将状态连接在一起:

select status, person from a
union all
select concat(married.status, ' & ', kids.status) status, kids.person
from a kids 
join a married on kids.Person = married.Person
where kids.Status = 'Has Kids' and married.Status = 'Married'

这将为您提供示例中的确切输出。

Sample SQL Fiddle

或者您可以按照建议使用for xml path的相关子查询:

SELECT Status, Person FROM A 
UNION ALL
SELECT Status = LTRIM(STUFF((
          SELECT '& ' + a.Status
          FROM a 
          WHERE a.Person = a1.Person
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''))
        , person 
FROM A A1 GROUP BY Person HAVING COUNT(Status) = 2