SQL Wave Sequencing

时间:2016-09-30 16:07:57

标签: sql-server-2008 tsql

以下是关注表的记录列表。我需要在SQL 2008中从图1到图2转换SQL查询。

图2所做的是对Weight Desc进行排序,然后在下一个STO值之后转到Asc。

我认为它涉及Group By和%2 ???

*Figure 1*
Item    SEL     STO      Weight 
1       ABC     A        80.00 
2       ABC     A        65.00 
3       ABC     A        50.00 
4       ABC     A        35.00 
5       ABC     A        20.00 
6       ABC     B        80.00 
7       ABC     B        65.00 
8       ABC     B        50.00 
9       ABC     B        35.00 
10      ABC     B        20.00 
11      ABC     C        80.00 
12      ABC     C        65.00 
13      ABC     C        50.00 
14      ABC     C        35.00 
15      ABC     C        20.00 
16      ABC     D        80.00 
17      ABC     D        65.00 
18      ABC     D        50.00 
19      ABC     D        35.00 
20      ABC     D        20.00 
*Figure 2*
Item    SEL     STO      Weight 
1       ABC     A        80.00 
2       ABC     A        65.00 
3       ABC     A        50.00 
4       ABC     A        35.00 
5       ABC     A        20.00 
10      ABC     B        20.00 
9       ABC     B        35.00 
8       ABC     B        50.00 
7       ABC     B        65.00 
6       ABC     B        80.00 
11      ABC     C        80.00 
12      ABC     C        65.00 
13      ABC     C        50.00 
14      ABC     C        35.00 
15      ABC     C        20.00 
20      ABC     D        20.00 
19      ABC     D        35.00 
18      ABC     D        50.00 
17      ABC     D        65.00 
16      ABC     D        80.00 

2 个答案:

答案 0 :(得分:2)

;with cte
as
(select *, dense_rank() over (order by sto) as rownum 
from #temp
)
select * from cte
order by 
rownum,
case when (rownum %2)=0  then wght  end asc,
case when (rownum %2)<>0 then wght  end desc

答案 1 :(得分:1)

另一种不需要窗口函数的方法,并创建一个更简单的执行计划:

SELECT *
FROM sampleData
ORDER BY STO, [Weight] * CASE ASCII(STO)%2 WHEN 1 THEN [Weight] ELSE -[Weight] END;