我遇到一个问题,我必须检索产品的所有可能位置并将它们组织在一个栏中。在我们的仓库中,一种产品可以占据多个位置,当我提取数据时,数据的组织方式如下:
SKID LOCATION
---- --------
A S1
A S2
A S3
B S4
B S5
C S6
我想对其进行组织,以便将位置组织在单独的列中。
SKID LOCATION1 LOCATION2 LOCATION3
---- --------- --------- ---------
A S1 S2 S3
B S4 S5 -
C S6 - -
如果可以做到,怎么办呢?
答案 0 :(得分:0)
这将使您更接近-
SELECT
SKID,
LISTAGG(LOCATION,',') WITHIN GROUP(
ORDER BY
SKID,LOCATION
) as location
FROM
(
SELECT
'A' AS SKID,
'S1' AS LOCATION
FROM
DUAL
UNION
SELECT
'A' AS SKID,
'S2' AS LOCATION
FROM
DUAL
UNION
SELECT
'A' AS SKID,
'S3' AS LOCATION
FROM
DUAL
UNION
SELECT
'B' AS SKID,
'S4' AS LOCATION
FROM
DUAL
UNION
SELECT
'B' AS SKID,
'S5' AS LOCATION
FROM
DUAL
UNION
SELECT
'C' AS SKID,
'S6' AS LOCATION
FROM
DUAL
)
GROUP BY
SKID;
输出-
SKID,LOCATION
A,S1,S2,S3
B,S4,S5
C,S6
答案 1 :(得分:0)
假设您知道结果集中所需的最大列数,则可以使用条件聚合或pivot
:
select skid,
max(case when seqnum = 1 then location end) as location_1,
max(case when seqnum = 2 then location end) as location_2,
max(case when seqnum = 3 then location end) as location_3
from (select t.*, row_number() over (partition by skid order by location) as seqnum
from t
) t
group by skid;
如果您不知道最大值,那么可以使用动态SQL(execute immediate
),listagg()
,嵌套表或JSON。