我正在使用DB2 V7r1(因此很遗憾没有listagg)。我需要能够将item(ItemNum)的所有描述都用一个逗号分隔。我有一个查询,发现有这种工作方式,但无法按项目编号过滤结果。它将与前100行数据一起正常工作,但是如果我尝试过滤掉表格下100,000行的项目,那将永远耗费时间。
* EDIT,我要补充一点,该表包含1,460,072条记录,并且一个“项/操作”最多可以包含60个“描述”条目,因此,如果有人知道一种可以预过滤结果的方法或一种更有效的方法,做到这一点,我将不胜感激
这是我的桌子:PARTS
ItemNum OpSequence DscNum Description
A-123 10 2 Desc Line 1
A-123 10 4 Desc Line 2
A-123 10 6 Desc Line 3
A-123 20 2 Desc Line 1
A-123 20 4 Desc Line 2
Z-555 10 2 Desc Line 1
Z-555 10 4 Desc Line 2
这是我需要的结果(需要通过ItemNum和OpSequence进行过滤)
ItemNum OpSequence Description
A-123 10 Desc Line 1, Desc Line 2, Desc Line 3
这是我使用的查询
with x (ItemNum, OpSequence, cnt, list, empno, len) as
(select z.ItemNum, z.OpSequence,
(select count(*) from PARTS y
where y.ItemNum=z.ItemNum
group by y.ItemNum),
cast(z.Description as varchar(100)),
rrn(z), 1
from PARTS z
where z.ItemNum = 'A-123' (HERE IS WHERE I AM TRYING TO FILTER)
union all
select x.ItemNum,
x.OpSequence,
x.cnt,
strip(x.list) ||', '|| e.Description,
rrn(e),
x.len+1
from PARTS e, x
where e.ItemNum = x.ItemNum and rrn(e) > x.empno
)
select ItemNum,OpSequence, list
from x
where len=cnt
答案 0 :(得分:1)
答案 1 :(得分:0)
如果给定项目的行数有限,则此SQL将为您工作..例如,如果您有11行以上,则需要对其进行扩展
SELECT ItemNum, OpSequence
, MAX(CASE WHEN DscNum = 1 THEN Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 2 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 3 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 4 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 5 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 6 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 7 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 8 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum = 9 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum =10 THEN ', ' || Description ELSE '' END)
|| MAX(CASE WHEN DscNum =11 THEN ', ' || Description ELSE '' END)
AS Description
FROM
PARTS
WHERE
ItemNum = 'A-123'
GROUP BY
ItemNum, OpSequence
答案 2 :(得分:0)
我已经在iSeries V7R1上使用XMLAGG进行类似操作,请尝试以下操作。请注意,以下内容并不能说明您需要获得最低的OpSequence,但确实会为您提供描述字段的逗号分隔列表。
SELECT ItemNum,
OpSequence,
DscNum,
TRIM(REPLACE(
REPLACE(
REPLACE(
XMLSERIALIZE(XMLAGG(XMLELEMENT(NAME "x", TRIM(Description)) ) AS VARCHAR(1000))
, '</x><x>', ',')
, '<x>', '')
, '</x>', '')) AS Description
FROM x
GROUP BY ItemNum, OpSequence, DscNum