4

我被困在一个查询上,

在哪里我有 52 周的数据,我可以根据 sysdate 通过获取周数并与数据周数进行比较来安排这些数据。现在我想做的是如果当前的周数是 10 我想按照 sysdate 周数 week10,week9,week8 ....week11 的降序排列所有周,

用这个查询

select "Weekly","Quarter","SALES","Monthly",week_number from fiscal_calendar
where week_number <= TO_CHAR(TO_DATE(sysdate,'DD-mon-YYYY'),'iw') 
order by  week_number desc;

我能够将数据排序到第 1 周,但我想继续序列,比如在第 11 周结束,所以我做错了什么,请指教

4

2 回答 2

4

如果我理解正确你可以试试

SELECT * FROM
(SELECT "Weekly","Quarter","SALES","Monthly",week_number FROM fiscal_calendar
  WHERE week_number <= TO_NUMBER(TO_CHAR(SYSDATE,'IW')) 
  ORDER BY  week_number desc) t1
UNION ALL
SELECT * FROM 
(SELECT "Weekly","Quarter","SALES","Monthly",week_number FROM fiscal_calendar
  WHERE week_number > TO_NUMBER(TO_CHAR(SYSDATE,'IW'))
  ORDER BY  week_number) t2

这是简化的SQLFiddle 示例

于 2013-03-11T08:20:32.823 回答
0

我们可以在 order by 子句中使用case()(or ) ...decode()

order by case 
           when week_number = to_number(to_char(sysdate, 'WW')) then 1
           when week_number < to_number(to_char(sysdate, 'WW')) then 2
           when week_number > to_number(to_char(sysdate, 'WW')) then 3
         end ASC
         , week_number DESC
于 2013-03-11T09:02:32.507 回答