如何分组和连接查询结果

时间:2015-06-25 13:56:19

标签: sql

说我有这样的查询:

Select 
    dept, 
    person_id
form 
    depts

返回以下结果

dept              person_id
-----             ---------
'sales'              2
'management'         2
'sales'              3
'administrative'     4
'management'         4

如何进行返回以下结果的查询?

 depts                         person_id
 -----                         ---------
'sales, management'             2
'sales'                         3
'administrative, management'    4

2 个答案:

答案 0 :(得分:1)

不适用于PostgreSql,但适用于Ms Sql Server

select person_id,
       (select stuff((select ', ' + dept from TableName t2
        where t2.person_id = t1.person_id
        for xml path('')), 1, 2, '')) as depts 
from TableName t1
group by person_id

修改

;with cte as(your super big query here)

select person_id,
       (select stuff((select ', ' + dept from cte t2
        where t2.person_id = t1.person_id
        for xml path('')), 1, 2, '')) as depts 
from cte t1
group by person_id

答案 1 :(得分:1)

你可以试试这个:

SELECT group_concat(dept),person_id FROM depts group by person_id ;//mysql