0

我有下面的表格。

在此处输入图像描述

我喜欢按日期更新 ID,然后按用户更新。

例如

在此处输入图像描述

谢谢

4

2 回答 2

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]
于 2012-11-04T13:31:32.947 回答
1

SQL小提琴

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

结果

| 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 |
于 2012-11-04T13:39:16.093 回答