小编典典

使用iSeries的SQL将多个行值连接为1行

sql

首先,我要感谢肯特使我尽可能地解决了这个问题。但是现在我需要扩大他在这里所做的事情。

为避免您不得不阅读他的文章,他解决的问题是将字符串数据从多行连接到结果表中的单行中。例如:

台式车:

  • Make Model
  • Ford Fusion
  • Chevy Tahoe
  • Honda Odyssey
  • Ford Taurus
  • Ford Focus
  • Chevy Malibu

结果:

  • Make Model
    Chevy Malibu, Tahoe
    Ford Focus, Taurus, Fusion
    *Honda Odyssey

这是通过SQL语句完成的:

WITH numbered_sets(make, model, curr, prev) AS (
   SELECT make, model,
       ROW_NUMBER() OVER (PARTITION BY make ORDER BY model) AS curr,
       ROW_NUMBER() OVER (PARTITION BY make ORDER BY model) -1 AS prev
   FROM inventory)
SELECT make,
       MAX (TRIM(L ',' FROM
             CAST(SYS_CONNECT_BY_PATH(model, ',') AS VARCHAR(256)) ))
FROM numbered_sets
START WITH curr = 1
CONNECT BY make = PRIOR make AND prev = PRIOR curr
GROUP BY make

我能够将其调整到自己的桌子上,并获得大部分想要的方式。但出于我的目的,我需要在分组中添加其他列。例如:

台式车:

  • Make Type Model
  • Ford Sedan Fusion
  • Chevy SUV Tahoe
  • Honda Minivan Odyssey
  • Ford Sedan Taurus
  • Ford Sedan Focus
  • Chevy Sedan Malibu
  • Ford SUV Escape
  • Ford SUV Explorer
  • Chevy Sedan Impala

对于结果,我正在寻找:

  • Make Type Model
  • Chevy Sedan Malibu, Impala
  • Chevy SUV Tahoe
  • Ford Sedan Fusion, Taurus, Focus
  • Ford SUV Escape, Explorer
  • Honda Minivan Odyssey

是否有人对我需要添加到原始语句中的内容有任何想法,以便能够添加TYPE列,并相应地添加GROUP?我尝试了一些事情,但是我怀疑我需要使用CONNECT_BY_PATH语句来做一些事情,但我不确定。

谢谢


阅读 254

收藏
2021-04-07

共1个答案

小编典典

我认为您只需要在考虑查询的正确点上集成类型。

如果无法测试,我认为这很接近;但我可能错过了一些东西

WITH numbered_sets(make, type, model, curr, prev) AS (
   SELECT make, type, model,
       ROW_NUMBER() OVER (PARTITION BY make, Type ORDER BY Make, Type, model) AS curr,
       ROW_NUMBER() OVER (PARTITION BY make, type ORDER BY Make, type, model) -1 AS prev
   FROM inventory)
SELECT make, Type
       MAX (TRIM(L ',' FROM
             CAST(SYS_CONNECT_BY_PATH(model, ',') AS VARCHAR(256)) ))
FROM numbered_sets
START WITH curr = 1
CONNECT BY make = PRIOR make AND prev = PRIOR curr and type = prior type
GROUP BY make, type

也许我们需要先更改连接方式,然后再进行连接…尽管我还不明白为什么这会有所帮助…

CONNECT BY concat(make,type) = PRIOR concat(make,type) AND prev = PRIOR curr
2021-04-07