2014-10-29 44 views
0

我有这个datset:形成一个TSQL查询排名和分类日期字段

create table #date_example 
(
date_val datetime, rownum int 
) 

insert #date_example values('3/1/14',1) 
insert #date_example values('3/1/14',2) 
insert #date_example values('3/1/14',3) 
insert #date_example values('2/1/14',4) 
insert #date_example values('1/3/14',5) 

select --top 1 with ties 
date_val, 
ROW_NUMBER() OVER(PARTITION BY rownum ORDER BY date_val DESC) AS 'RowNum' 

from #date_example 
order by date_val 
desc 

随着输出:

date_val RowNum 
2014-03-01 00:00:00.000 1 
2014-03-01 00:00:00.000 1 
2014-03-01 00:00:00.000 1 
2014-02-01 00:00:00.000 1 
2014-01-03 00:00:00.000 1 

但我想,而不是输出:

date_val RowNum 
2014-03-01 00:00:00.000 1 
2014-03-01 00:00:00.000 1 
2014-03-01 00:00:00.000 1 
2014-02-01 00:00:00.000 2 
2014-01-03 00:00:00.000 3 

所以我希望RowNum成为包含关系的排名。我怎样才能做到这一点?

+0

你尝试RANK(或DENSE_RANK(? – 2014-10-29 14:59:41

+0

rownum的分区 - 在数据集rownum中是独一无二的。而使用rownum和RowNum真的让人困惑 - tsql不区分大小写。 – Paparazzi 2014-10-29 15:02:33

回答

1

我发现从另一个职位的答案:))

select 
date_val, 
Rank() OVER(ORDER BY date_val DESC) AS 'RowNum' 

from #date_example 
+1

有趣,你没有看到[我的评论](http://stackoverflow.com/questions/26633648/how-to-form-a-tsql-query-that-ranks-and-categorizes-date-field#comment41875027_26633648 )? – 2014-10-29 16:25:14