带有JOINS的Oracle Select查询

时间:2018-08-22 16:24:40

标签: sql oracle

我有下面的Oracle SQL查询,它运行正常

 Select Cage.BARCODE Cg, CagePen.BARCODE Pen
 FROM LOCATION_ENTITY CagePen
 LEFT JOIN LOCATION_ENTITY Cage ON SUBSTR(CagePen.FULL_LOCATION, -6)=Cage.BARCODE
 WHERE CagePen.FULL_LOCATION = 'Current'

我得到的回复是

      CG    PEN
  CGE100    CP4265
  CGE100    CP4264
  CGE101    CP4266
  CGE101    CP4267
  CGE102    CP4268
  CGE102    CP4269

现在,我尝试合并重复CG的响应

   CG            PEN
 CGE100   CP4265,   CP4264
 CGE101   CP4266,   CP4267
 CGE102   CP4268,   CP4269

此查询是否应使用agg()

1 个答案:

答案 0 :(得分:3)

您正在寻找listagg()

SELECT Cage.BARCODE as Cg, LISTAGG(CagePen.BARCODE, ',') WITHIN GROUP (ORDER BY CagePen.BARCODE) as Pens
FROM LOCATION_ENTITY CagePen LEFT JOIN
     LOCATION_ENTITY Cage 
     ON SUBSTR(CagePen.FULL_LOCATION, -6) = Cage.BARCODE
WHERE CagePen.FULL_LOCATION = 'Current'
GROUP BY Cage.BARCODE;