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

huangapple go评论92阅读模式
英文:

SQL Query, Create new column instead a new row SQL Oracle

问题

尝试创建一个查询以获取所有产品及其相关的日期和包装:

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;
英文:

i try create a query to get all products and your repectives dates and packs:

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;

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

Result:

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

But i need the query return a table like this:

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

Or this:

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

Tks for attention =]]]]]]]]

EDIT:

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

答案1

得分: 1

你尝试过使用 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;
英文:

Have you tried to use 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;

答案2

得分: 1

使用LISTAGGDISTINCT可以解决问题。

LISTAGG聚合函数通过使用新的DISTINCT支持去重。

由于您不希望有重复的包/日期,以下是如何实现的:

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;

演示在这里

英文:

Using LISTAGG DISTINCT can do the trick.

The LISTAGG aggregate function supports duplicate elimination by using the new DISTINCT.

Since you dont want duplicated packs/dates this is how to do it :

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

huangapple
  • 本文由 发表于 2023年3月12日 17:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定