SQL Server SELECT Rank()和数据分组

时间:2016-05-17 04:44:39

标签: sql-server select group-by rank with-statement

请帮我解决这个具体问题。

这是我的示例查询

with cte as 
(
select entryID,LogDateTime,logtype[logtype],batch,
rank() over (partition by logType 
           order by logdatetime) rnk
from Emp_TimeLog
where cast(LogDateTime as date) = '2016-05-17'
) select entryID,LogDateTime,logType,batch, rnk 
from cte order by LogDateTime 

结果是这样的

2016-05-17 11:57:44.000 1   1   1
2016-05-17 11:57:53.000 5   1   1
2016-05-17 11:57:58.000 6   1   1
2016-05-17 11:58:10.000 2   1   1
2016-05-17 11:58:18.000 1   2   2
2016-05-17 11:58:25.000 3   1   1
2016-05-17 11:58:32.000 4   1   1
2016-05-17 11:58:42.000 5   2   2
2016-05-17 11:58:49.000 6   2   2
2016-05-17 11:58:55.000 2   2   2

但我想要的就是这样。

2016-05-17 11:57:44.000 1   1   1
2016-05-17 11:57:53.000 5   1   1
2016-05-17 11:57:58.000 6   1   1
2016-05-17 11:58:10.000 2   1   1
2016-05-17 11:58:18.000 1   2   2
2016-05-17 11:58:25.000 3   2   2
2016-05-17 11:58:32.000 4   2   2
2016-05-17 11:58:42.000 5   2   2
2016-05-17 11:58:49.000 6   2   2
2016-05-17 11:58:55.000 2   2   2

最后两列是BatchRank, 而第3列是logType。 它应该是logType的批次,其中LogType组是1,2,3,4,5,6。 所以,对于每1组,它是另一批,我需要将它放在最后2列。

请帮助我解决这个问题。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

你只需要在排名中修改顺序......如:

rank() over (partition by logType 
           order by batch) rnk