日期:2014-05-19  浏览次数:20450 次

求一算法
表结构和数据如下:
星期ID,星期一,星期二,星期三,星期四,星期五
          1,         1,           2,           3,           4,           5
          2,         3,           1,         10,           3,           6
          3,。。。。。。

想找出四周内最大的三个值,sql怎么写?

------解决方案--------------------
select top 3 * from
(
select * from
(
select 星期ID , 星期一 as value
union all
select 星期ID , 星期二 as value
union all
select 星期ID , 星期三 as value
union all
select 星期ID , 星期四 as value
union all
select 星期ID , 星期五 as value
) t
order by value desc
) m

------解决方案--------------------
select top 3 * from
(
select * from
(
select 星期ID , 星期一 as value
union all
select 星期ID , 星期二 as value
union all
select 星期ID , 星期三 as value
union all
select 星期ID , 星期四 as value
union all
select 星期ID , 星期五 as value
) t where BETWEEN(1 and 4)
order by desc
) m

------解决方案--------------------
select top 3 * from
(
select 星期ID , 星期一 as value from 表
union all
select 星期ID , 星期二 as value from 表
union all
select 星期ID , 星期三 as value from 表
union all
select 星期ID , 星期四 as value from 表
union all
select 星期ID , 星期五 as value from 表
) t
order by value desc

------解决方案--------------------
set rowcount 3

select * from
(
select 星期ID , 星期一 as value
union all
select 星期ID , 星期二 as value
union all
select 星期ID , 星期三 as value
union all
select 星期ID , 星期四 as value
union all
select 星期ID , 星期五 as value
) t
order by value desc
set rowcount 0

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

create table T(星期ID int,星期一 int, 星期二 int,星期三 int,星期四 int,星期五 int)
insert T select 1,1,2,3,4,5
union all select 2,3,1,10,3,6
union all select 3,1,12,13,5,8
union all select 4,5,4,14,3,6
union all select 5,100,120,1,50,60

select top 3 值=星期一 from
(
select 星期ID, 星期一 from T
union all
select 星期ID, 星期二 from T
union all
select 星期ID, 星期三 from T
union all
select 星期ID, 星期四 from T
union all
select 星期ID, 星期五 from T
)tmp where 星期ID <5
order by 星期一 desc

--result

-----------
14
13
12

(3 row(s) affected)