2017-07-28 58 views
0

我有一組數據。我想產生最後一個字段 - > 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

您的排名標準是什麼?像白天秩序,然後醫生的名字,然後行動等? – JRG

+0

只有約會和醫師。行動對於排名並不重要。 – KOMAEI

+0

2016-01-02 Dr.John Call 1'爲什麼會在日期不同的時候排名爲1?這是一個錯字嗎? – BJones

回答

1

這可不是用dense_rank(),但在SQL Server 2012+可以使用lag()窗函數來確定何時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 

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

回報:

+------------+-----------+--------+--------+ 
| 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 | 
+------------+-----------+--------+--------+ 

膨化樣品達再與多位內科醫生合作。

+0

我們可能在一次約會中有兩位醫生。在這種情況下,這段代碼不起作用!假設約翰博士在2016-01-08有記錄? – KOMAEI

+0

@KOMAEI你爲什麼不更新你的問題,並顯示你會找到什麼結果? – SqlZim

+0

當然。我確實改變了數據集。 – KOMAEI