日期:2014-05-18  浏览次数:20531 次

排行榜的查询问题
如下面的表格
id num date 
01 2 2005-9-1
02 1 2005-9-2
11 2 2005-9-2
03 11 2005-9-10
21 1 2005-9-10
02 5 2005-9-12
07 22 2005-9-15
01 1 2005-9-20
.. .. .....
31 105 2006-12-21
.. .. .....
12 21 2007-10-22
... ... ....

商品,日期,还有数量都是随意的.

以周(月)作为统计周期,截止到现在,希望得到连续4周(月)以上排行销售榜首(尾)的商品是什么?
或者查询一种商品销售排名最高,最低排名的时期和名次.

相同排名,保留名次.如1,2,3,3 ,则2排名第3.以次类推.




------解决方案--------------------

以周(月)作为统计周期,截止到现在,希望得到连续4周(月)以上排行销售榜首(尾)的商品是什么?
不太明白,需要统计的是最近30天的(10-22,9-22)还是从月初到月底的一个月(10-22,10-1)?

------解决方案--------------------
SQL code
--或者查询一种商品销售排名最高,最低排名的时期和名次. 
select * , 排名 = (select count(1) from 
(
  select id,convert(varchar(10),date,120) [month],sum(num) sum_num from tb id,convert(varchar(10),date,120)
) t 
where id = a.id and num > a.num) + 1 from 
(
  select id,convert(varchar(10),date,120) [month],sum(num) sum_num from tb id,convert(varchar(10),date,120)
) a 
order by t.id , t.排名

------解决方案--------------------
乌龟真强,佩服