我有下表。
我喜欢根据日期更新 ID
,然后按用户。
答案 0 :(得分:3)
您可以使用Common Table Expression
进行此操作,并从原始表中加入,例如:
WITH newID
AS
(
SELECT [User], [DATE],
ROW_NUMBER() OVER (PARTITION BY bb.[User]
ORDER BY DATE ASC) RN
FROM table1 bb
)
UPDATE a
SET a.ID = b.RN
FROM table1 a INNER JOIN
newID b ON a.[User] = b.[User] AND
a.[Date] = b.[Date]
答案 1 :(得分:1)
MS SQL Server 2008架构设置:
create table YourTable
(
MYUser char(3),
Date date,
ID int
)
insert into YourTable(MYUser, Date) values
('U55', '2012-10-05'),
('U55', '2012-10-10'),
('U22', '2012-10-06'),
('U55', '2012-10-01'),
('U55', '2012-10-07'),
('U22', '2012-10-04'),
('U55', '2012-10-09'),
('U22', '2012-10-02'),
('U22', '2012-10-03'),
('U55', '2012-10-08')
查询1 :
update T
set ID = rn
from
(
select ID,
row_number() over(partition by MYUser order by Date) as rn
from YourTable
) as T
select *
from YourTable
<强> Results 强>:
| MYUSER | DATE | ID |
----------------------------
| U55 | 2012-10-05 | 2 |
| U55 | 2012-10-10 | 6 |
| U22 | 2012-10-06 | 4 |
| U55 | 2012-10-01 | 1 |
| U55 | 2012-10-07 | 3 |
| U22 | 2012-10-04 | 3 |
| U55 | 2012-10-09 | 5 |
| U22 | 2012-10-02 | 1 |
| U22 | 2012-10-03 | 2 |
| U55 | 2012-10-08 | 4 |