[英]Rank Visits SQL Server 2014
我有一个按ID进行医生就诊的样本表。 我希望按年龄对问题进行排名,并按ID进行划分,以便我可以按ID对同一问题的第2次和第3次访问进行一些统计计算。 请注意:我有一个更大的数据集,所以我正在寻找可以解决这个问题的东西。
到目前为止,我有
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
代码运行,但等级计算不正确。 请帮忙。
据我了解,您需要按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,'Toe',60)。 要枚举它们,请将RANK
替换为ROW_NUMBER
我相信你想要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 |
+----+-----+---------+-----+-----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.