根据优先级选择查询

时间:2014-06-12 06:59:40

标签: sql sql-server

我有桌子

Id  createdonutc 
1    2014-05-29 10:14:00.240
2    2014-05-29 10:16:58.587
3    2014-06-01 11:32:54.140
4    2014-05-29 10:48:40.427
6    2014-06-01 2:1:54.140

我想只获取订单日期(没时间)desc

的数据
Id  createdonutc                    rank

3    2014-06-01 11:32:54.140         1
6    2014-06-01 2:1:54.140           1
1    2014-05-29 10:14:00.240         2
2    2014-05-29 10:16:58.587         2
4    2014-05-29 10:48:40.427         2

我试过了:

SELECT
    id, 
    P.createdonutc,  
    ROW_NUMBER() OVER (PARTITION BY cast(p.[CreatedOnUtc] AS DATE) ORDER BY cast(p.[CreatedOnUtc] AS DATE) desc) as num
FROM
    news p
ORDER BY num

它显示结果没有变化。我怎样才能让它起作用?

2 个答案:

答案 0 :(得分:2)

请尝试使用DENSE_RANK()

SELECT
    id, 
    P.createdonutc,  
    Dense_Rank() OVER (ORDER BY cast(p.[CreatedOnUtc] AS DATE) desc) as num
FROM
    news p
ORDER BY num

答案 1 :(得分:0)

Row_Number为每一行生成不同的数字,即使值相等,也可以获得您想要使用的内容DENSE_RANK

SELECT id, createdonutc
     , dense_rank() OVER (order by cast(createdonutc as date) DESC)
FROM   News

SQLFiddle demo