如何连接两个行值

时间:2017-01-09 09:58:14

标签: sql oracle11g

我使用下面的查询,我连接四个值,它对我有用,但现在对于其中一个列(ADDRESS_LINE),我有两个值,我想连接所有。

    (SELECT LDR.ADDRESS_LINE
  || ' , '
  || LOC.CITY
  ||' , '
  || LOC.postal_code
  ||' , '
  || LOC.country_code3_gid
FROM LOCATION LOC,
  LOCATION_ADDRESS LDR,
  SHIPMENT SH
WHERE SH.SOURCE_LOCATION_GID = LOC.LOCATION_GID
AND LOC.LOCATION_GID         = LDR.LOCATION_GID
AND SH.SHIPMENT_GID          = :P_SHIPMENT_ID
)

但是现在对于ADDRESS_LINE我有三个值,我希望包含在同一个查询中。

我知道我们可以通过LISTAGG实现这一目标但不知何故我没有得到正确的结果

1 个答案:

答案 0 :(得分:0)

这是你的查询,清理了一下:

SELECT (LDR.ADDRESS_LINE || ' , ' || LOC.CITY ||' , ' ||
        LOC.postal_code ||' , ' || LOC.country_code3_gid
       )
FROM LOCATION LOC JOIN
     LOCATION_ADDRESS LDR
     ON LOC.LOCATION_GID = LDR.LOCATION_GID JOIN
     SHIPMENT SH
     ON SH.SOURCE_LOCATION_GID = LOC.LOCATION_GID
WHERE SH.SHIPMENT_GID = :P_SHIPMENT_ID;

样本数据和期望的结果将阐明您真正想要的内容。以下是关于合理推测的一些想法。

您可以使用listagg()

将这些组合成一行
SELECT LISTAGG(LDR.ADDRESS_LINE || ' , ' || LOC.CITY ||' , ' ||
               LOC.postal_code ||' , ' || LOC.country_code3_gid,
               ';'
              ) WITHIN GROUP (ORDER BY ?)
FROM LOCATION LOC JOIN
     LOCATION_ADDRESS LDR
     ON LOC.LOCATION_GID = LDR.LOCATION_GID JOIN
     SHIPMENT SH
     ON SH.SOURCE_LOCATION_GID = LOC.LOCATION_GID
WHERE SH.SHIPMENT_GID = :P_SHIPMENT_ID;

?用于指定地址行排序的列。

请注意,这很容易出现溢出的字符串。此外,您可能需要GROUP BY。如果您想要在同一个城市内的所有地址行,那么您可以这样做:

SELECT LISTAGG(LDR.ADDRESS_LINE || ' , ' || LOC.CITY ||' , ' ||
               LOC.postal_code ||' , ' || LOC.country_code3_gid,
               ';'
              ) WITHIN GROUP (ORDER BY ?)
FROM LOCATION LOC JOIN
     LOCATION_ADDRESS LDR
     ON LOC.LOCATION_GID = LDR.LOCATION_GID JOIN
     SHIPMENT SH
     ON SH.SOURCE_LOCATION_GID = LOC.LOCATION_GID
WHERE SH.SHIPMENT_GID = :P_SHIPMENT_ID
GROUP BY LOC.CITY, LOC.postal_code, LOC.country_code3_gid;