DB2 SQL 更新超过 1 个与子查询相关的列
DB2 SQL update more than 1 columns correlating with subquery
我是 DB2 的新手,但不是 SQL 的新手,新的 DB2 SQL 更新与 DB2 LUW V9.5 中的子查询相关。我的 Table 如下所示:
在第 3 行和第 7 行中,我需要从第 4 行和第 8 行 (SCD) 更新 ACTIVE = 0
和 VALID_TO = VALID_FROM
。我 select 使用以下语句的数据:
SELECT T2.COL1, T2.COL1_HIST, T2.ACTIVE, T2.VALID_FROM, T2.VALID_TO, T3.VALID_FROM
FROM TMP.TABLE01 T2 INNER JOIN
(
SELECT COL1, MAX(COL1_HIST) MAX_HIST FROM TMP.TABLE01 WHERE
ACTIVE = 1
GROUP BY COL1
HAVING Count(*)>1
)T1 ON T2.COL1 = T1.COL1 AND T2.COL1_HIST < T1.MAX_HIST
INNER JOIN TMP.TABLE01 T3 ON T1.COL1 = T3.COL1 AND T1.MAX_HIST = T3.COL1_HIST
WHERE T2.ACTIVE = 1
要在 SQL 世界更新,我可以使用以下语句:
UPDATE T2 SET T2.ACTIVE = 0,T2.VALID_TO=T3.VALID_FROM
FROM TMP.TABLE01 T2 INNER JOIN
(
SELECT COL1, MAX(COL1_HIST) MAX_HIST FROM TMP.TABLE01 WHERE
ACTIVE = 1
GROUP BY COL1
HAVING Count(*)>1
)T1 ON T2.COL1 = T1.COL1 AND T2.COL1_HIST < T1.MAX_HIST
INNER JOIN TMP.TABLE01 T3 ON T1.COL1 = T3.COL1 AND T1.MAX_HIST = T3.COL1_HIST
WHERE T2.ACTIVE = 1
在 DB2 (DB2 LUW V9.5) 世界中怎么会这样?
我知道 Stack Overflow 中的类似问题,但它对我没有帮助:( link
非常感谢
试试这个:
merge into table01 a using
(
select rownumber() over(partition by col1 order by col1_hist desc) rn_, t.*
from table01 t
where active=1
) m on m.rn_=1 and a.active=1 and a.col1=m.col1 and a.col1_hist<>m.col1_hist
when matched then update set active=0, valid_to=m.valid_from;
对于具有相同 col1
.[=20 的一组记录中具有最高 col1_hist
的每一行,内部子选择的 rn_
列的值为 1
=]
我们用每个组的正确 valid_from
值更新除这些行之外的所有其他活动行。
我是 DB2 的新手,但不是 SQL 的新手,新的 DB2 SQL 更新与 DB2 LUW V9.5 中的子查询相关。我的 Table 如下所示:
ACTIVE = 0
和 VALID_TO = VALID_FROM
。我 select 使用以下语句的数据:
SELECT T2.COL1, T2.COL1_HIST, T2.ACTIVE, T2.VALID_FROM, T2.VALID_TO, T3.VALID_FROM
FROM TMP.TABLE01 T2 INNER JOIN
(
SELECT COL1, MAX(COL1_HIST) MAX_HIST FROM TMP.TABLE01 WHERE
ACTIVE = 1
GROUP BY COL1
HAVING Count(*)>1
)T1 ON T2.COL1 = T1.COL1 AND T2.COL1_HIST < T1.MAX_HIST
INNER JOIN TMP.TABLE01 T3 ON T1.COL1 = T3.COL1 AND T1.MAX_HIST = T3.COL1_HIST
WHERE T2.ACTIVE = 1
要在 SQL 世界更新,我可以使用以下语句:
UPDATE T2 SET T2.ACTIVE = 0,T2.VALID_TO=T3.VALID_FROM
FROM TMP.TABLE01 T2 INNER JOIN
(
SELECT COL1, MAX(COL1_HIST) MAX_HIST FROM TMP.TABLE01 WHERE
ACTIVE = 1
GROUP BY COL1
HAVING Count(*)>1
)T1 ON T2.COL1 = T1.COL1 AND T2.COL1_HIST < T1.MAX_HIST
INNER JOIN TMP.TABLE01 T3 ON T1.COL1 = T3.COL1 AND T1.MAX_HIST = T3.COL1_HIST
WHERE T2.ACTIVE = 1
在 DB2 (DB2 LUW V9.5) 世界中怎么会这样?
我知道 Stack Overflow 中的类似问题,但它对我没有帮助:( link
非常感谢
试试这个:
merge into table01 a using
(
select rownumber() over(partition by col1 order by col1_hist desc) rn_, t.*
from table01 t
where active=1
) m on m.rn_=1 and a.active=1 and a.col1=m.col1 and a.col1_hist<>m.col1_hist
when matched then update set active=0, valid_to=m.valid_from;
对于具有相同 col1
.[=20 的一组记录中具有最高 col1_hist
的每一行,内部子选择的 rn_
列的值为 1
=]
我们用每个组的正确 valid_from
值更新除这些行之外的所有其他活动行。