高级SQL更新语句

时间:2018-05-16 12:03:34

标签: sql sql-server

我有一张这样的表

+------+-----------+----------+
|  ID  |  Column1  |  Column2 |  
+------+-----------+----------+
|    1 |      x    |      a   |
|    2 |      x    |      b   |
|    3 |      x    |      c   |
|    4 |      y    |      d   |
|    5 |      y    |      e   |
|    6 |      y    |      f   |    
+------+-----------+----------+

我正在尝试用"替换重复的Column1值。 &#34 ;;

所以喜欢这个

+------+-----------+----------+
|  ID  |  Column1  |  Column2 |  
+------+-----------+----------+
|    1 |      x    |      a   |
|    2 |           |      b   |
|    3 |           |      c   |
|    4 |      y    |      d   |
|    5 |           |      e   |
|    6 |           |      f   |    
+------+-----------+----------+

这就是我的尝试:

Update #temp 

SET status = '' 
where id != (select top 1 id from #temp where status != (select min(status) from #temp));

这是临时表。我正在使用SQL服务器

3 个答案:

答案 0 :(得分:1)

不确定通过更新此功能会获得什么好处,但您仍然可以像使用MACHINE10一样执行此操作。

CTE

答案 1 :(得分:1)

使用IIF()IN Sql server

尝试此脚本
IF OBJECT_ID('Tempdb..#t')IS NOT NULL
DROP TABLE #t;

;WITH CTE(ID,Column1,Column2)
AS
(
SELECT 1 ,'x','a' UNION ALL  
SELECT 2 ,'x','b' UNION ALL  
SELECT 3 ,'x','c' UNION ALL  
SELECT 4 ,'y','d' UNION ALL  
SELECT 5 ,'y','e' UNION ALL  
SELECT 6 ,'y','f' 
)
SELECT * INTO #t FROM CTE c   

表更新前

SELECT * FROM #t

更新查询

 ;WITH CTE
    AS
    (
    SELECT ID,
           IIF(Column1=LAG(Column1)OVER(ORDER BY ID),'',Column1)AS Column1,
          Column2 
    FROM #t
    )
    UPDATE t
        SET t.Column1=ct.Column1
    FROM #t t
    INNER JOIN CTE ct
        ON ct.ID=t.ID

    SELECT * FROM #t

我们也可以使用Subquery更新

UPDATE t
    SET t.Column1=Dt.Column1
FROM #t t
INNER JOIN
    (SELECT ID,
           IIF(Column1=LAG(Column1)OVER(ORDER BY ID),'',Column1)AS Column1,
          Column2 
    FROM #t
    )Dt
ON Dt.ID=t.ID

结果,演示:http://rextester.com/MLR80836

ID  Column1 Column2
--------------------
1     x       a
2             b
3             c
4     y       d
5             e
6             f

答案 2 :(得分:0)

我不建议更新实际信息,但您可以使用SELECT声明

来表达
select ID, 
      (case when row_number() over (partition by Column1 order by id) = 1 
            then Column1 
        end) as Column1, 
      Column2
from table t;

您也可以使用subquery

重新表达它
select ID, (case when Seq = 1 then Column1 end) as Column1, Column2
from (select *,
             row_number() over (partition by Column1 order by id) Seq
      from table
     )t;