2017-02-26 131 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 | 
+----+-----+---------+-----+-----+