我是SQL Server的新手,我有以下问题:是否有可能重新编号列中的行?
例如:
id date name
1 2016-01-02 John
2 2016-01-02 Jack
3 2016-01-02 John
4 2016-01-02 John
5 2016-01-03 Jack
6 2016-01-03 Jack
7 2016-01-04 John
8 2016-01-03 Jack
9 2016-01-02 John
10 2016-01-04 Jack
我希望所有" Johns"以id 1开始并继续(2,3,4等)和所有" Jacks"约翰"约翰"已完成(5,6,7等)。谢谢!
答案 0 :(得分:1)
id
应该只是你用于连接的内部标识符等 - 我不会改变它。但您可以使用窗口函数查询这样的编号:
SELECT ROW_NUMBER() OVER (ORDER BY CASE name WHEN 'John' THE 1 ELSE 2 END) AS rn,
date,
name
FROM mytable
答案 1 :(得分:0)
我希望这有帮助..
declare @t table (id int ,[date] date,name varchar(20))
insert into @t
( id, date, name )
values (1,'2016-01-02','John')
,(2,'2016-01-02','Jack')
,(3,'2016-01-02','John')
,(4,'2016-01-02','John')
,(5,'2016-01-03','Jack')
,(6,'2016-01-03','Jack')
,(7,'2016-01-04','John')
,(8,'2016-01-03','Jack')
,(9,'2016-01-02','John')
,(10,'2016-01-04','Jack')
select
row_number() over(order by name,[date]) as ID,
date ,
name
from
@t
order by name
答案 2 :(得分:-1)
您可以使用ROW_NUMBER
窗口函数根据您的要求重新编号行,而不是重新编号id列。例如:
SELECT ROW_NUMBER() OVER(PARTITION BY name ORDER BY date) as rowid,date,name
FROM tablename