有没有一种方法可以根据结果行中的一个值将 DB2 SQL 语句结果集中的单行转换为多行?

Is there a way to turn a single row from a DB2 SQL statement result set into multiple rows based on one value from that resulting row?

如果我有这样的 SQL 查询:

SELECT A.W, A.X, B.Y, B.Z 
FROM A 
INNER JOIN B ON A.value1 = B.value2;

它返回这样一行:

 W | X | Y | Z
---+---+---+--
 w | x | y | z

有没有办法修改该语句,使结果像这样table

 W | X | Y1  | Y2  | Z
---+---+-----+-----+---
 w | x | y+0 | y+1 | z
 w | x | y+2 | y+3 | z
 w | x | y+4 | y+5 | z
 w | x | y+6 | y+7 | z
 w | x | y+8 | y+9 | z

其中 Y1Y2 列派生自原始 y

使用 returns 整数 0、2、4、6 和 8 的 CTE,并将其交叉连接到您的查询:

WITH cte(n) AS (VALUES (0), (2), (4), (6), (8))
SELECT A.W, A.X, 
       B.Y + c.n AS Y1,
       B.Y + c.n + 1 AS Y2, 
       B.Z 
FROM A 
LEFT JOIN B ON A.value1 = B.value2
CROSS JOIN  cte AS c;

如果您想要一组动态整数,请使用递归 CTE:

WITH cte(n) AS (
  SELECT 0 FROM SYSIBM.SYSDUMMY1    
  UNION ALL
  SELECT n + 2 
  FROM cte 
  WHERE n < 8 -- change 8 to the number that you want
)
SELECT A.W, A.X, 
       B.Y + c.n AS Y1,
       B.Y + c.n + 1 AS Y2, 
       B.Z 
FROM A 
LEFT JOIN B ON A.value1 = B.value2
CROSS JOIN  cte AS c;