根据当前系统日期对数据进行排序

时间:2013-03-11 08:11:02

标签: sql oracle

我被困在一个查询上,

在哪里我有52周的数据,我可以根据sysdate安排获取周数并与数据周数比较。 现在我要做的是,如果当前周数为10,我想按降序安排所有周,例如取决于sysdate周数周10,周9,周8 .........周11,

使用此查询

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周结束 所以我做错了什么 请建议

2 个答案:

答案 0 :(得分: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 example

答案 1 :(得分:0)

我们可以在order by子句中使用case()(或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