2017-02-16 173 views
0

我有一個有一百萬條記錄的表。我需要根據基於特定id的列的現有「非空」記錄來更新一些null列。我試着用一個查詢,它似乎工作正常,但我沒有信心,它將能夠完全按照我需要的方式更新所有這100萬條記錄。我爲您提供一些示例數據我的桌子的外觀like.Any幫助將不勝感激更新所有其他記錄基於單個記錄

SELECT * INTO #TEST FROM (
SELECT 1 AS EMP_ID,10 AS DEPT_ID,15 AS ITEM_NBR ,NULL AS AMOUNT,NULL AS ITEM_NME 
UNION ALL 
SELECT 1,20,16,500,'ABCD' 
UNION ALL 
SELECT 1,30,17,NULL,NULL 

UNION ALL 

SELECT 2,10,15,1000,'XYZ' 
UNION ALL 
SELECT 2,30,16,NULL,NULL 
UNION ALL 
SELECT 2,40,17,NULL,NULL 
) AS A 

的樣本數據:

+--------+---------+----------+--------+----------+ 
| EMP_ID | DEPT_ID | ITEM_NBR | AMOUNT | ITEM_NME | 
+--------+---------+----------+--------+----------+ 
|  1 |  10 |  15 | NULL | NULL  | 
|  1 |  20 |  16 | 500 | ABCD  | 
|  1 |  30 |  17 | NULL | NULL  | 
|  2 |  10 |  15 | 1000 | XYZ  | 
|  2 |  30 |  16 | NULL | NULL  | 
|  2 |  40 |  17 | NULL | NULL  | 
+--------+---------+----------+--------+----------+ 

預期結果:

+--------+---------+----------+--------+----------+ 
| EMP_ID | DEPT_ID | ITEM_NBR | AMOUNT | ITEM_NME | 
+--------+---------+----------+--------+----------+ 
|  1 |  10 |  15 | 500 | ABCD  | 
|  1 |  20 |  16 | 500 | ABCD  | 
|  1 |  30 |  17 | 500 | ABCD  | 
|  2 |  10 |  15 | 1000 | XYZ  | 
|  2 |  30 |  16 | 1000 | XYZ  | 
|  2 |  40 |  17 | 1000 | XYZ  | 
+--------+---------+----------+--------+----------+ 

我試過,但我無法得出它是否正確更新所有100萬條記錄的結論。

SELECT * FROM #TEST T 
inner JOIN #TEST T1 ON T1.EMP_ID=T.EMP_ID 
WHERE T1.AMOUNT IS NOT NULL 

UPDATE T SET AMOUNT=T1.AMOUNT 
FROM #TEST T 
inner JOIN #TEST T1 ON T1.EMP_ID=T.EMP_ID 
WHERE T1.AMOUNT IS not NULL 

回答

0

我一直在使用內使用UPDATE加入

UPDATE T 
SET T.AMOUNT = X.AMT,T.ITEM_NME=X.I_N 
FROM #TEST T 
JOIN 
(SELECT EMP_ID,MAX(AMOUNT) AS AMT,MAX(ITEM_NME) AS I_N 
FROM #TEST 
GROUP BY EMP_ID) X ON X.EMP_ID = T.EMP_ID 
0
SELECT * into #Test1 
FROM #TEST 
WHERE AMOUNT IS NOT NULL 

對於記錄驗證運行此查詢第一

SELECT T.AMOUNT, T1.AMOUNT, T1.EMP_ID,T1.EMP_ID 
FROM #TEST T 
inner JOIN #TEST1 T1 ON T1.EMP_ID=T.EMP_ID 
WHERE T.AMOUNT IS NULL 

Begin Trans 

UPDATE T 
SET T.AMOUNT=T1.AMOUNT, T.ITEM_NME= = T1.ITEM_NME 
FROM #TEST T 
inner JOIN #TEST1 T1 ON T1.EMP_ID=T.EMP_ID 
WHERE T.AMOUNT IS NULL 

rollback 
0
SELECT EMP_ID,MAX(AMOUNT) as AMOUNT MAX(ITEM_NAME) as ITEM_NAME 
      INTO #t 
    FROM #TEST 
    GROUP BY EMP_ID 


UPDATE t SET t.AMOUNT = t1.AMOUNT, t.ITEM_NAME = t1.ITEM_NAME 
FROM #TEST t INNER JOIN #t t1 
ON t.emp_id = t1.emp_id 
WHERE t.AMOUNT IS NULL and t.ITEM_NAME IS NULL 

使用MAX一ggregate函數獲取每個員工的金額和項目名稱,然後用這些值替換金額和項目名稱的值。對於驗證,使用COUNT函數來計算金額和項目名稱值爲空的行數。如果行數爲零,則表格更新正確

相關問題