是否可以根据 T-SQL 中另一个 window 函数的结果对数据集进行排名?
Is it possible to rank a dataset by the result of another window function in T-SQL?
有什么方法可以根据另一个 window 函数的结果对数据集进行排名吗?
例如,我有一个类似下面的查询:
select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
order by
sess_prcnt desc
我想做的是按 sess_prcnt
列对国家/地区进行排名。
添加像 rank() over(order by sess_prcnt)
这样的行或使用 CTE 会产生错误。
提前致谢!
您说使用 CTE 会产生错误 - 它们会导致什么样的错误?例如,执行
之类的任何问题
; WITH A AS
(select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
)
SELECT *, rank() OVER (order by sess_prct DESC) AS rnk
FROM A
order by
sess_prcnt desc
或类似的使用它作为 FROM 子句的一部分
SELECT *, rank() OVER (order by sess_prct DESC) AS rnk
FROM
(select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
) A
order by
sess_prcnt desc
您可能还想确保为您的任务使用适当的排名函数 - ROW_NUMBER, RANK, or DENSE_RANK
有什么方法可以根据另一个 window 函数的结果对数据集进行排名吗?
例如,我有一个类似下面的查询:
select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
order by
sess_prcnt desc
我想做的是按 sess_prcnt
列对国家/地区进行排名。
添加像 rank() over(order by sess_prcnt)
这样的行或使用 CTE 会产生错误。
提前致谢!
您说使用 CTE 会产生错误 - 它们会导致什么样的错误?例如,执行
之类的任何问题; WITH A AS
(select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
)
SELECT *, rank() OVER (order by sess_prct DESC) AS rnk
FROM A
order by
sess_prcnt desc
或类似的使用它作为 FROM 子句的一部分
SELECT *, rank() OVER (order by sess_prct DESC) AS rnk
FROM
(select distinct
country,
cast(sum(Sessions) over (partition by country) as float) / cast(sum(sessions) over() as float) as sess_prcnt
from
GoogleAnalytics.dbo.SiteVisitsLog
) A
order by
sess_prcnt desc
您可能还想确保为您的任务使用适当的排名函数 - ROW_NUMBER, RANK, or DENSE_RANK