我还在学习SQL Server,最近我遇到了排名问题(不确定我是否应该使用排名)。
我正在尝试将排名排序如下,但我无法通过在SQL服务器中使用row_number(over)或任何排名函数来实现。
[加入] table1中的内容有Cust_Code,Week和T_Mode,下面显示的是CustA。基本上我想知道CustA,他首先使用Air,然后Water在上周的时间里再次切换到Air。
**** Required Output ******
Week T_Mode Rank
201301 Air 1
201303 Water 2
201305 Water 2
201306 Water 2
201311 Air 3
i used Row_Number but it does not give what I want.
select *
, row_number()over(partition by T_Mode order by week) as Rank
from table1
the output returned
Week T_Mode Rank
201301 Air 1
201303 Water 1
201305 Water 2
201306 Water 3
201311 Air 2
任何建议都会受到欢迎。谢谢!
答案 0 :(得分:1)
Declare @t table(Week1 int,T_Mode varchar(20))
insert into @t values(201301,'Air'),(201303,'Water'),(201305,'Water'),(201306,'Water'),(201311,'Air')
;with cte as
(
select top 1 week1,t_mode,1 [Rank] from @t order by week1
union all
select b.week1,b.t_mode,case when a.T_Mode=b.T_Mode then a.Rank else a.Rank+1 end [Rank] from @t b
outer apply cte a
where b.Week1>a.week1 and b.T_Mode<>a.T_Mode
)
select distinct * from cte
答案 1 :(得分:0)
这是一个适用于SQL Server 2012的解决方案:
select
week, t_mode,
sum(change) over (order by week rows unbounded preceding) [rank]
from (
select *,
case when
(select top 1 t_mode
from table1
where week < t1.week
order by week desc) <> t1.t_mode then 1 else 0 end [change]
from table1 t1
) x
这是SQL 2008的低效版本:
;with cte as (
select *,
case when
(select top 1 t_mode
from table1
where week < t1.week
order by week desc) <> t1.t_mode then 1 else 0 end [change]
from table1 t1
)
select
week, t_mode,
(select sum(change) from cte where week <= x.week) [rank]
from cte x