更新所有其他记录基于单个记录

时间:2017-02-16 07:32:48

标签: sql-server sql-server-2008 sql-update

我有一张包含一百万条记录的表格。我需要根据现有的' not null'更新一些空列。特定基于id的列的记录。我尝试了一个查询,似乎工作正常,但我不相信它能够按照我需要的方式更新所有这100万条记录。我为您提供了一些样本数据,我的表格如何。感谢您的帮助

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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聚合函数获取每位员工的金额和项目名称,然后将金额和项目名称的null值替换为这些值。对于验证,使用COUNT函数计算值为amount和item name的行数为null。如果行数为零,则表格正确更新