2017-05-01 35 views
0

http://sqlfiddle.com/#!15/157ad/3多個組的Posgresql JSON聚合。

是否可以按多個列進行分組,然後將結果放入該聚合中的表中。

我試圖要求數據庫告訴我找到所有的貨物,並且每個貨物屬於該貨物的貨櫃是什麼,以及每個貨物的地點是什麼。我可以爲一個分組做到這一點,但我無法找出兩個分組的子句。是否有可能在單個sql查詢中提出這個問題?

回答

0
select 
    s.shipmentName, 
    array_agg(distinct sc.pk_shipmentContainerId) as container, 
    array_agg(distinct l.locationName) as location 
from 
    shipment s 
    inner join 
    shipmentContainer sc on s.pk_shipmentId = sc.fk_shipmentId 
    inner join 
    shipmentMove sm on s.pk_shipmentId = sm.fk_shipmentId 
    inner join 
    location l on sm.fk_locationId = l.pk_locationId 
group by s.pk_shipmentId, 1 
order by s.pk_shipmentId 
; 
      shipmentname    | container |      location       
-------------------------------------+---------------+------------------------------------------------------- 
1.shipment of bananas - Loc 1,2,3,4 | {1,2,3}  | {"Location 1","Location 2","Location 3","Location 4"} 
2.shipment of apples Loc 1,2,3,4 | {4}   | {"Location 1","Location 2","Location 3","Location 4"} 
3.more bananas Loc 1,2,4,5   | {5,6,7,8,9} | {"Location 1","Location 2","Location 4","Location 5"} 
5.lots of pants Loc 5,3,2,1   | {10,11,12,13} | {"Location 1","Location 2","Location 3","Location 5"}