gpt4 book ai didi

sql - 合并非结构化表中的行

转载 作者:行者123 更新时间:2023-11-29 13:26:26 24 4
gpt4 key购买 nike

我有这个非结构化表,其中 (1) itemID 有多个与之关联的 receptCodes。我需要做的是在一行中显示与不同 orderID 关联的每个 receptCode。当前的表结构类似于这样:

    itemID  | receptString
=============================
itemID1 | receptString1
itemID1 | receptString2
itemID1 | receptString3
itemID1 | receptString4
itemID2 | receptString5
itemID2 | receptString6

期望的输出:

    itemID    | receptString | receptString  | receptString | receptString |
============================================================================
itemID1 | receptString1 | receptString2 | receptString3 | receptString4 |
itemID2 | receptString5 | receptString6 |

为此编写查询的正确方法是什么?我尝试使用多个 CASE 语句和 GROUP BY,但我正在努力解决这个问题的逻辑。每个 orderID 最多只能有 (5) 个 receptString,但可以在 1 – 5 个 receptString 之间变化。 receptStrings 可以是字符、符号和数字的组合。我不担心是否出现 NULL。这只是我需要的一部分,但却是我正在努力解决的问题。我正在 PostgreSQL 和 Oracle SQL 中对此进行测试。

* 更新 *

谢谢大家的建议。这个问题最终比我们最初预期的要严重一些(我提供的示例表是一个非常大的馅饼中的一小部分),所以我们决定采用不同的方法。再次感谢。

最佳答案

在 11g 中测试。

这里我使用了一个临时分隔符~。如果您认为您的字符串字符有这个,您可以使用 |chr(10)chr(13) 或任何其他分隔符。它会工作得很好。

此外,列名不能与您想要的相同。我附加了 1,2,3 等等。您可以根据需要更改它们。

    with tbl1 (itemID  , receptString) as(
select 'itemID1','receptString1' from dual union all
select 'itemID1','receptString2' from dual union all
select 'itemID1','receptString3' from dual union all
select 'itemID1','receptString4' from dual union all
select 'itemID2','receptString5' from dual union all
select 'itemID2','receptString6' from dual
), tbl2 as(
select itemid,listagg(receptString,'~') within group (order by itemid) || '~' as concstr
from tbl1
group by itemid
)
SELECT tbl2.itemid,REGEXP_SUBSTR(concstr ,'([^~]*)(\~)', 1, 1, NULL, 1 ) as receptString1,
REGEXP_SUBSTR(concstr ,'([^~]*)(\~)', 1, 2, NULL, 1 ) as receptString2,
REGEXP_SUBSTR(concstr ,'([^~]*)(\~)', 1, 3, NULL, 1 ) as receptString3,
REGEXP_SUBSTR(concstr ,'([^~]*)(\~)', 1, 4, NULL, 1 ) as receptString4,
REGEXP_SUBSTR(concstr ,'([^~]*)(\~)', 1, 5, NULL, 1 ) as receptString5
from tbl2

首先,我使用 listagg 连接列并添加分隔符。然后我使用 regep_substr 将它们分成几列。对于不存在的列,根据此输出,它们将为空。

输出

 ITEMID     RECEPTSTRING1   RECEPTSTRING2   RECEPTSTRING3   RECEPTSTRING4  RECEPTSTRING5
itemID1 receptString1 receptString2 receptString3 receptString4
itemID2 receptString5 receptString6

关于sql - 合并非结构化表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33094974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com