在“一个”表格中,一对多加入并按ID进行分组

时间:2015-05-22 18:29:45

标签: sql postgresql

我有两个表:Person和事件,其中Person有很多事件

我想通过person.id加入表,但我不希望查询返回每个事件的记录。相反,我希望它返回每人附加许多事件的记录。这可能吗?

例如我得到:

["person_id" : "1", "eventid" :"1"]
["person_id" : "1", "eventid" :"2"]
["person_id" : "1", "eventid" :"3"]

但我想要的是

["person_id" : "1", ["eventid" :"1", "eventid" :"2", "eventid" :"3"]]

2 个答案:

答案 0 :(得分:0)

使用array_agg

select person.id, array_agg(eventid)
from person
 inner join events
 on person.id = events.person_id
group by person_id

答案 1 :(得分:0)

请查看我的内联注释,当使用group时我们可以使用sum()这样的函数来添加整数,你的基本问题是在group by上连接字符串,这有点不直接。

--This is how would I do in MS SQL 
--Person-Event Data
CREATE TABLE #person (person_id INT, event_id INT)

INSERT INTO #person
SELECT 1,1
UNION ALL 
SELECT 1,2
UNION ALL
SELECT 1,3
UNION ALL 
SELECT 2,1
UNION ALL
SELECT 2,2
UNION ALL
SELECT 3,1

--Concept is to use Group By and concat strings in inner query
--Inner query is on same table as outer table,
--using group by column of outer query in where clause of inner query to filter results
--STUFF(string, start index, length of string which is to be replaced, replace with string)
--used stuff to remove the leading comma 
SELECT person_id, pevents=STUFF((
                SELECT ',' +CONVERT(VARCHAR(100),event_id)
                FROM #person pinner 
                WHERE pinner.person_id=pouter.person_id FOR XML PATH('')),1,1,'')
--bonus formatting, dont know if you need this          
,  pevents_formatted=STUFF((
                SELECT ',' +'"eventid" : "' + CONVERT(VARCHAR(100),event_id)+'"'
                FROM #person pinner 
                WHERE pinner.person_id=pouter.person_id FOR XML PATH('')),1,1,'[ ')+' ]'    


            ,person_with_pevents_formatted_result=  '[ "personid" :"'+CONVERT(VARCHAR(100),person_id)+'" ,' +   
            STUFF((
                SELECT ',' +'"eventid" : "' + CONVERT(VARCHAR(100),event_id)+'"'
                FROM #person pinner 
                WHERE pinner.person_id=pouter.person_id FOR XML PATH('')),1,1,'[ ')+' ] ]'


FROM #person pouter
GROUP BY  person_id

DROP TABLE #person

希望这就是你要找的东西。