密集排名组

时间:2017-07-28 16:55:52

标签: sql-server lag dense-rank

我有一组数据。我想生成最后一个字段 - > D_Rank

date  physician  action  D_Rank
2016-01-01  Dr.John  visit  1
2016-01-01  Dr.John  Call   1
2016-01-02  Dr.John  Call   1
2016-01-03  Dr.Jane  Call   2
2016-01-04  Dr.Jane  Call   2
2016-01-05  Dr.Jane  Visit  2
2016-01-06  Dr.John  NoCall 3
2016-01-07  Dr.John  NoCall 3
2016-01-08  Dr.John  Visit  3
2016-01-08  Dr.Jane  Visit  4
2016-01-08  Dr.Jane  Call   4
2016-01-08  Dr.Joe   Visit  5
2016-01-09  Dr.Joe   Call   5

非常感谢先进。

1 个答案:

答案 0 :(得分:1)

这不使用lag(),但在SQL Server 2012+中,您可以使用physician窗口函数来确定select date, physician, action , change = sum(change) over (order by date, physician desc) from ( select * , change = case when physician = lag(t.physician) over (order by t.date, t.physician desc) then 0 else 1 end from t ) s 何时更改,分配该值并将其与另一个窗口函数如下:

+------------+-----------+--------+--------+
|    date    | physician | action | change |
+------------+-----------+--------+--------+
| 2016-01-01 | Dr.John   | Visit  |      1 |
| 2016-01-01 | Dr.John   | Call   |      1 |
| 2016-01-02 | Dr.John   | Call   |      1 |
| 2016-01-03 | Dr.Jane   | Call   |      2 |
| 2016-01-04 | Dr.Jane   | Call   |      2 |
| 2016-01-05 | Dr.Jane   | Visit  |      2 |
| 2016-01-06 | Dr.John   | NoCall |      3 |
| 2016-01-07 | Dr.John   | NoCall |      3 |
| 2016-01-08 | Dr.John   | Visit  |      3 |
| 2016-01-08 | Dr.Jane   | Call   |      4 |
| 2016-01-08 | Dr.Jane   | Visit  |      4 |
| 2016-01-09 | Dr.John   | Visit  |      5 |
| 2016-01-09 | Dr.Jane   | Call   |      6 |
| 2016-01-09 | Dr.Jane   | Visit  |      6 |
+------------+-----------+--------+--------+

rextester演示:http://rextester.com/MQDS34484

返回:

{{1}}

与多名医生一起扩展了另一天的样本数据。