0

我有这张桌子:

ID   |Type|Date
17494|NULL|2013-09-04 15:00:00.000  
17577|NULL|2013-09-04 15:00:00.000  
17639|NULL|2013-09-04 17:00:00.000  
17701|NULL|2013-09-04 17:00:00.000

我想按日期分组,然后更新每个日期组第一行的类型字段并将其设置为“F”,其余(可能是多个)将它们设置为“V”

结果:

ID   |Type|Date
17494|F   |2013-09-04 15:00:00.000  
17577|V   |2013-09-04 15:00:00.000  
17639|F   |2013-09-04 17:00:00.000  
17701|V   |2013-09-04 17:00:00.000
4

3 回答 3

1

SQL2005+的解决方案:

DECLARE @MyTable TABLE
(
    ID      INT NOT NULL,
    [Type]  CHAR(1) NULL,
    [Date]  DATETIME NOT NULL 
);
INSERT  @MyTable (ID, [Type], [Date])
SELECT 17494, NULL, '2013-09-04 15:00:00.000' UNION ALL
SELECT 17577, NULL, '2013-09-04 15:00:00.000' UNION ALL
SELECT 17639, NULL, '2013-09-04 17:00:00.000' UNION ALL
SELECT 17701, NULL, '2013-09-04 17:00:00.000';

WITH MyTableWithRowNum
AS
(
    SELECT  *, ROW_NUMBER() OVER(PARTITION BY x.[Date] ORDER BY x.ID) AS RowNum
    FROM    @MyTable x
)
UPDATE  MyTableWithRowNum
SET     [Type] = CASE WHEN RowNum = 1 THEN 'F' ELSE 'V' END;

SELECT * FROM @MyTable;

结果:

ID          Type Date
----------- ---- -----------------------
17494       F    2013-09-04 15:00:00.000
17577       V    2013-09-04 15:00:00.000
17639       F    2013-09-04 17:00:00.000
17701       V    2013-09-04 17:00:00.000
于 2013-09-17T18:19:23.857 回答
0

尝试这个:

UPDATE T
SET Type = CASE WHEN IDD = 1 THEN 'F' ELSE 'V' END
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Date ORDER BY ID) IDD , * FROM tbl) T;

SQL 小提琴演示

于 2013-09-17T18:24:16.553 回答
0

嗨,没有直接查询可以实现这一点。但是我们可以通过变通来实现这一点

With #temptable as(
select Row_number() over( PARTITION BY date1 ORDER BY date1) Rank, *
from tablea)

update TableA set Type = 'F'
where id in (select Id from #temptable where Rank = 1)

update TableA set Type = 'V'
where Type is null

select * from TableA

我检查了 SQLFiddle,它的工作http://sqlfiddle.com/#!3/bfb05/6/0

于 2013-09-17T18:30:11.503 回答