首先,我要感谢Kent Milligan和他在http://www.mcpressonline.com/sql/techtip-combining-multiple-row-values-into-a-single-row-with-sql-in-db2-for-i.html的文章让我尽可能地解决这个问题。但现在我需要扩展他在这里所做的事情。
为了避免你不得不转到他的文章,他解决的问题是将多行中的字符串数据连接到结果表中的单行。例如:
Table Cars:
结果:
这是通过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
我能够将它调整到我自己的桌子上,并获得我想要的大部分方式。但就我的目的而言,我需要为分组添加一个额外的列。例如:
Table Cars:
对于结果,我一直在寻找:
有没有人对我需要添加到原始语句的内容有任何想法,以便能够相应地添加TYPE列和GROUP?我尝试了一些东西,但我怀疑我需要用CONNECT_BY_PATH语句做些什么,我只是不确定是什么。
谢谢
答案 0 :(得分: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