SQL Server, Count Consecutive Weeks Record Has Been in Top 5 -
i have complicated query:
select rs.name, rs.sumhits, rs.weeknumber from( select name, weeknumber, sum(hits) sumhits, rank() on (partition weeknumber order sum(hits) desc) rank ( select name, datediff ( day, (select dateadd(wk, datediff(wk,0,(select min(table2.date) table2)), 0)), (table2.date) ) / 7 weeknumber, hits table1 inner join table2 on table1.nameid = name.id ) group name, weeknumber ) rs rank <= 5 order weeknumber desc
which provides me top 5 "names" "hits" each week.
i add field calculates number of consecutive weeks each name in week's top 5 has been in top five. so, column have value of 1 if name in week's top 5 not in last week's, value of 3 if name week's top 5 had been in top 5 previous 2 weeks, etc.
what best way accomplish this?
you think of query cte , add further information in follow-up ctes or final select:
something this:
with mycte ( query here!!! ) select *, furtherdata mycte
but - commented - query seems "enhanceable" :-) maybe post sample data , expected result...
Comments
Post a Comment