如何使用sql查询为每一行设置标志1,2和3?通过订购日期字段des / asc
非常感谢您的帮助。
例如:
Id Name date flag 9278 david 02/12/2012 1 4343 sharon 21/11/2012 2 4783 elizabeth 17/11/2012 3 47846 john 08/10/2012 1 78347 chris 17/09/2012 2 37379 Joe 18/06/2012 3
答案 0 :(得分:1)
您的问题有点不清楚,但您可能需要使用ROW_NUMBER函数和模运算符的组合:
with temp as
(
select 9278 as num, 'david' as name, CONVERT( datetime, '02/12/12',3) as date
UNION
select 4343, 'sharon', CONVERT( datetime, '21/11/12',3)
UNION
select 4783, 'elizabeth', CONVERT( datetime, '17/11/12',3)
UNION
select 47846, 'john', CONVERT( datetime, '08/10/12',3)
UNION
select 78347, 'chris' , CONVERT( datetime, '17/09/12',3)
UNION
select 37379, 'Joe' , CONVERT( datetime, '18/06/12',3)
)
select *,
((ROW_NUMBER() OVER (ORDER BY date desc) + 2) % 3) + 1 as Flag
from temp
如果某些编程语言正在使用这些数据,我可能会尝试在那里添加数字,而不是在SQL代码中。
答案 1 :(得分:0)
我认为这是sql2008:
select *, ROW_NUMBER() OVER (ORDER BY date) as Flag from YourTable