SQL查询,创建新列而不是新行SQL Oracle

epggiuax  于 2023-03-17  发布在  Oracle
关注(0)|答案(2)|浏览(179)

我尝试创建一个查询,以获得所有产品和您的repectives日期和包:

SELECT 
p.id,
d.date,
pc.pack
FROM Products p
LEFT JOIN Dates d ON p.id = d.id
LEFT JOIN Packs pc ON p.id = pc.id;

第一节第一节第一节第一节第一节第二节第一节
结果:

但是我需要查询返回一个如下的表:

或者这个:

注意事项=]]]]]]]
编辑:

ID  PRODUCT
1   AAA
2   BBB
3   CCC
4   DDD

ID  DATE
1   2022-05-01
1   2023-02-08
2   2021-10-25
3   2020-04-18
3   2021-06-07
3   2023-01-19
4   2022-12-21

ID  PACK
1   4
2   6
2   12
3   8
3   16
4   1
4   10
4   20
2j4z5cfb

2j4z5cfb1#

使用LISTAGGDISTINCT就可以达到这个目的。
LISTAGG聚合函数通过使用新的DISTINCT支持重复消除。
由于您不希望重复的 Package /日期,这是如何做到:

with cte as (
  SELECT p.id, d.date_, pc.pack
  FROM products p
  LEFT JOIN dates d ON p.id = d.id
  LEFT JOIN packs pc ON p.id = pc.id
)
select id,
  listagg (DISTINCT date_,', ' on overflow truncate with count) 
  within group (order by date_) dates,
  listagg (DISTINCT pack,', ' on overflow truncate with count) 
  within group (order by pack) packs
from cte
group by id;

Demo here

z4iuyo4d

z4iuyo4d2#

您是否尝试过使用STRING_AGG?

SELECT p.id, LISTAGG(d.date, ', ') WITHIN GROUP(
ORDER BY
    d.date
) AS dates, LISTAGG(pc.pack, ', ') WITHIN GROUP(
ORDER BY
    pc.pack
) AS packs
FROM Products p
LEFT JOIN Dates d ON p.id = d.id
LEFT JOIN Packs pc ON p.id = pc.id
GROUP BY p.id;

相关问题