Sql Synapse如何更新最新记录
Sql Synapse How to update the latest records
Table 映射
| ID | CUST_ID | MEMID | CRE_DT | UPD_DT
----------------------------------------
| 1 | AA21 | NULL |20210101|20210101
| 2 | AA21 | MID01 |20210202|20210202
| 3 | AA50 | MID00 |20210101|20210101
Table 硕士
| ID | CUST_ID | NEW_MEMID
| 2 | AA21 | NW01
| 3 | AA50 | NW02
更新后的输出
Table 映射
| ID | CUST_ID | MEMID | CRE_DT | UPD_DT
----------------------------------------
| 1 | AA21 | NULL |20210101|20210101
| 2 | AA21 | NW01 |20210202|20210202
| 3 | AA50 | NW02 |20210101|20210101
我在更新地图中的数据时遇到问题,我只想更新最新的记录。
注意:1 CUST_ID : M ID 因此我需要按 cust_id 排序 upd_dt DESC,ID ASC 来获取最新的记录。
我只想更新行
ID = 2 CUST_ID = AA21
ID = 3 CUST_ID = AA50
UPDATE MAPPING
SET MEMID = NEW_MEMID
FROM
(SELECT DISTINCT
ID, CUST_ID, NEW_MEMID
FROM MASTER) SRC
WHERE (SRC.ID, SRC.CUST_ID) IN
(SELECT ID, CUST_ID
FROM
(SELECT
DISTINCT ID, CUST_ID,
ROW_NUMBER() OVER (PARTITION BY CUST_ID ORDER BY COALESCE(UPDATED_DATE, CREATED_DATE) DESC, ID ASC) RN
FROM MAPPING) LASTEST
WHERE RN = 1)
Parse error at line: 33, column: 42: Incorrect syntax near ','.
即WHERE (SRC.ID,SRC.CUST_ID) IN
假设 Azure Synapse 符合 T-SQL,您可以在此处使用可更新的 CTE:
WITH cte AS (
SELECT mp.MEMID, ms.NEW_MEMID,
ROW_NUMBER() OVER (PARTITION BY mp.CUST_ID
ORDER BY COALESCE(mp.UPD_DT, mp.CRE_DT)) rn
FROM MAPPING mp
INNER JOIN MASTER ms ON ms.CUST_ID = mp.CUST_ID
)
UPDATE cte
SET MEMID = NEW_MEMID
WHERE rn = 1;
Table 映射
| ID | CUST_ID | MEMID | CRE_DT | UPD_DT
----------------------------------------
| 1 | AA21 | NULL |20210101|20210101
| 2 | AA21 | MID01 |20210202|20210202
| 3 | AA50 | MID00 |20210101|20210101
Table 硕士
| ID | CUST_ID | NEW_MEMID
| 2 | AA21 | NW01
| 3 | AA50 | NW02
更新后的输出
Table 映射
| ID | CUST_ID | MEMID | CRE_DT | UPD_DT
----------------------------------------
| 1 | AA21 | NULL |20210101|20210101
| 2 | AA21 | NW01 |20210202|20210202
| 3 | AA50 | NW02 |20210101|20210101
我在更新地图中的数据时遇到问题,我只想更新最新的记录。
注意:1 CUST_ID : M ID 因此我需要按 cust_id 排序 upd_dt DESC,ID ASC 来获取最新的记录。
我只想更新行
ID = 2 CUST_ID = AA21
ID = 3 CUST_ID = AA50
UPDATE MAPPING
SET MEMID = NEW_MEMID
FROM
(SELECT DISTINCT
ID, CUST_ID, NEW_MEMID
FROM MASTER) SRC
WHERE (SRC.ID, SRC.CUST_ID) IN
(SELECT ID, CUST_ID
FROM
(SELECT
DISTINCT ID, CUST_ID,
ROW_NUMBER() OVER (PARTITION BY CUST_ID ORDER BY COALESCE(UPDATED_DATE, CREATED_DATE) DESC, ID ASC) RN
FROM MAPPING) LASTEST
WHERE RN = 1)
Parse error at line: 33, column: 42: Incorrect syntax near ','.
即WHERE (SRC.ID,SRC.CUST_ID) IN
假设 Azure Synapse 符合 T-SQL,您可以在此处使用可更新的 CTE:
WITH cte AS (
SELECT mp.MEMID, ms.NEW_MEMID,
ROW_NUMBER() OVER (PARTITION BY mp.CUST_ID
ORDER BY COALESCE(mp.UPD_DT, mp.CRE_DT)) rn
FROM MAPPING mp
INNER JOIN MASTER ms ON ms.CUST_ID = mp.CUST_ID
)
UPDATE cte
SET MEMID = NEW_MEMID
WHERE rn = 1;