我正在使用SQL Server 2005.请考虑以下示例:
表格定义和示例数据
create table my_table
(
issueid nchar(10) not null,
date datetime not null,
rate numeric(18,9),
rate_roll numeric(18,9)
);
insert into my_table
(issueid, date, rate)
values ('1', '20140131', '0.6'),
('3', '20140131', '0.6'),
('1', '20140228', '0.4'),
('2', '20140228', '0.4'),
('3', '20140228', '0.4'),
('1', '20140331', '0.7'),
('2', '20140331', '0.7'),
('3', '20140331', '0.7'),
('1', '20140430', '0.1'),
('2', '20140430', '0.1'),
('3', '20140430', '0.1');
我想为每个日期排名rate
列。我知道如何在一个日期执行此操作:
我的查询
select issueid, date, rate,
DENSE_RANK() over (order by rate desc) AS Rank
from my_table
where date = '20140131'
and rate is not null
order by Rank
你们有没有人可以帮我调整一下这个问题,以便我可以为每个日期做这个?提前谢谢!
答案 0 :(得分:3)
您正在寻找partition by
:
select issueid, date, rate,
DENSE_RANK() over (partition by date order by rate desc) AS Rank
from my_table
where rate is not null
order by date, Rank;
您可以随时将其更新:
with toupdate as (
select t.*
DENSE_RANK() over (partition by date order by rate desc) AS DayRank
from my_table t
where rate is not null
)
update toupdate
set rate_rank = dayrank;