SQL-排名月度数据集高、中、低
我有一个表格,其中包括月份、accountID和一组应用程序分数。我想创建一个新的专栏,为每月33%的结果的顶部、中部和底部提供“高”、“中”或“低” 如果我使用rank,我可以为一个月或整个数据集排序应用程序分数,但我不确定每月如何排序。此外,在我的sql server版本中,百分比排名不起作用SQL-排名月度数据集高、中、低,sql,sql-server,case,rank,percentile,Sql,Sql Server,Case,Rank,Percentile,我有一个表格,其中包括月份、accountID和一组应用程序分数。我想创建一个新的专栏,为每月33%的结果的顶部、中部和底部提供“高”、“中”或“低” 如果我使用rank,我可以为一个月或整个数据集排序应用程序分数,但我不确定每月如何排序。此外,在我的sql server版本中,百分比排名不起作用 select AccountID , ApplicationScore , rank() over (order by applicationscore asc) as Rank f
select
AccountID
, ApplicationScore
, rank() over (order by applicationscore asc) as Rank
from Table
然后我知道我需要将rank语句放入子查询中,然后使用case语句应用“high”、“medium”或“low”
select
AccountID
, case when rank <= total/3 then 'low'
when rank > total/3 and rank <= (total/3)*2 then 'medium'
when rank > (total/3)*2 then 'high' end ApplicationScore
from (subquery) a
SQL Server可能内置了一些东西来处理您的问题。但是我们可以很容易地使用计数比率来找到每个月的三个分数段。我们可以使用的比率是计数,按月份划分,按分数排序,除以整个月份的计数
WITH cte AS (
SELECT *,
1.0 * COUNT(*) OVER (PARTITION BY Month ORDER BY ApplicationScore) /
COUNT(*) OVER (PARTITION BY Month) AS cnt
FROM yourTable
)
SELECT
AccountID,
Month,
ApplicationScore,
CASE WHEN cnt < 0.34 THEN 'low'
WHEN cnt < 0.67 THEN 'medium'
ELSE 'high' END AS rank
FROM cte
ORDER BY
Month,
ApplicationScore DESC;
Ntile3工作得很好
select
AccountID
, Monthstart
, ApplicationScore
, ntile(3) over (partition by monthstart order by applicationscore) Rank
from table
你的预期产出是多少?您希望排名在每个月内,还是在整个数据集中?@TimBiegeleisen我希望我的表显示月份、帐户ID、应用程序核心、排名。排名实际上是月度排名,根据当月排名的前三分之一、中三分之一或后三分之一,排名为“低”、“中”或“高”