我有一张桌子:
Client | Date | Value 1 | Value 2 |
1 2013-11-08 159 159
1 2013-11-09 254 254
1 2013-12-05 512 512
1 2014-01-02 1200 1200
2 2013-11-10 189 189
2 2013-11-15 289 289
2 2013-12-22 585 585
2 2014-01-06 1650 1650
我需要在SQL中更新表格,如下所示:
Client | Date | Value 1 | Value 2 |
1 2013-11-08 159 1200
1 2013-11-09 254 1200
1 2013-12-05 512 1200
1 2014-01-02 1200 1200
2 2013-11-10 189 1650
2 2013-11-15 289 1650
2 2013-12-22 585 1650
2 2014-01-06 1650 1650
我们的想法是,对于每个客户,Value 2
将变为Value 1
Date
最近的位置。
答案 0 :(得分:5)
在SQL Server中,最好的方法是使用带有UPDATE
语句的CTE。下面的查询演示了您需要执行的操作的语法。您所要做的就是替换您的表名和列名。
;WITH MyUpdate
AS ( SELECT ClientId
,Value1
,ROW_NUMBER() OVER ( PARTITION BY ClientId ORDER BY MyDate DESC ) AS RowNum
FROM MyTable)
UPDATE MyTable
SET MyTable.Value2 = MyUpdate.Value1
FROM MyTable
INNER JOIN MyUpdate
ON MyUpdate.ClientID = MyTable.ClientID
AND RowNum = 1
答案 1 :(得分:0)
试试这个:
UPDATE TABLE1 T2 SET Value2 =
(SELECT T1.Value2 FROM TABLE1 T1 WHERE T1.Client = T2.Client AND
T1.Date = (SELECT MAX(T3.Date) FROM TABLE1 T3
WHERE T2.Client = T3.Client GROUP BY Client));