2017-02-26 170 views
0

enter image description hereRank訪問SQL Server 2014

我有一個醫生訪問樣本表的ID。我期望根據年齡排序問題,按照ID進行分區,這樣我就可以通過ID對第二次和第三次訪問同一問題做一些統計計算。請注意:我有一個更大的數據集,所以我正在尋找能夠解決這個問題的東西。

到目前爲止,我有

SELECT 
    ID, Age, Problem, COUNT(Problem) AS cnt, 
    RANK() OVER (PARTITION BY id ORDER BY Problem, Age ASC) AS rnk 
FROM 
    #Test1 
GROUP BY 
    ID, Problem, Age 
ORDER BY 
    Age ASC 

代碼運行,但排名計算不正確。請幫忙。

+2

什麼與你的預期輸出你的樣本數據?填寫你想要的等級,以及你想要的數量。 –

+0

預計: 1,2,1,1,3,1,1,2,1,1,2,1 –

+0

從理論上講,我希望排名標籤的所有出現的問題,以便我可以拉第二個如果存在問題的發生。 –

回答

0

據我所知,需要通過ID和問題分區:

CREATE TABLE #Test1 (ID int, Problem nvarchar(20), Age int) 

INSERT INTO #Test1 
VALUES 
(1,'Arm',50), 
(1,'Arm',52), 
(1,'Foot',54), 
(1,'Tongue',55), 
(1,'Arm',59), 
(2,'Toe',60), 
(2,'Toe',60), 
(2,'Arm',61), 
(3,'Tooth',75), 
(3,'Tooth',76), 
(3,'Knee',78) 

SELECT 
    ID, 
    Age, 
    Problem, 
    COUNT(*) OVER (PARTITION BY ID, Problem, Age) as cnt, 
    RANK() OVER (PARTITION BY ID, Problem ORDER BY Age) as rnk 
FROM #Test1 AS t 
ORDER BY t.Age 

DROP TABLE #Test1 

在這個解決方案,你會得到相同的秩= 1的數據(2, '腳趾',60)。一一列舉,與ROW_NUMBER

+0

讓我試試這個真快 –

+0

@KID_J你解決了你的問題嗎?你能接受這個答案嗎? – Backs

0

更換RANK我相信你想要的row_number()代替rank()

select 
    id 
    , Age 
    , Problem 
    , cnt = count(*) over (partition by id, Problem) 
    , rnk = row_number() over (partition by id, Problem order by Age) 
from t 
order by id, Age, Problem 

測試設置:http://rextester.com/DUWG50873

回報:

+----+-----+---------+-----+-----+ 
| id | Age | Problem | cnt | rnk | 
+----+-----+---------+-----+-----+ 
| 1 | 50 | Arm  | 3 | 1 | 
| 1 | 52 | Arm  | 3 | 2 | 
| 1 | 54 | Foot | 1 | 1 | 
| 1 | 55 | Tongue | 1 | 1 | 
| 1 | 59 | Arm  | 3 | 3 | 
| 2 | 60 | Toe  | 2 | 1 | 
| 2 | 60 | Toe  | 2 | 2 | 
| 2 | 61 | Arm  | 1 | 1 | 
| 3 | 75 | Tooth | 2 | 1 | 
| 3 | 76 | Tooth | 2 | 2 | 
| 3 | 78 | Knee | 1 | 1 | 
+----+-----+---------+-----+-----+