0

使用oracle数据库,表是这样的

id    sdate        offer
1   16-04-13       offer1
2   11-04-13       offer2
3   21-04-13       offer4
4   31-03-13       offer5
5   14-04-13       offer8
6   10-04-13       offer4
7   15-04-13       offer1

我想将周数计算为 w1 w2 等等sysdate。例子:

  • 对于id=1,sdate落在 16-04-13 所以它是week1
  • 对于id=5,sdate落在 14-04-13 所以它是week2

结果应该是这样的

id  week   offer
1    w1   offer1
5    w2   offer8
.............
4

4 回答 4

1

要将今天和前六天视为“第 1 周”,然后将之前的 7 天视为“第 2 周”,依此类推,请尝试以下操作:

SELECT
  id,
  'w' || TO_CHAR(TRUNC((TRUNC(SYSDATE) - sdate) / 7) + 1) as week,
  offer
FROM ... and so on
于 2013-04-22T13:47:02.663 回答
1

你也有一个格式。来自OTN

select to_char( date '2008-01-04', 'IW' ) from dual
于 2013-04-22T16:31:18.107 回答
0

One date minus another date gives their difference in days. Divide by seven to get difference in weeks. Use floor() to get rid of the remainder. Add 1 because you want to start at W1 not W0.

select id
        , sdate
        , 'W'||trim(to_char(floor((sysdate - sdate)/7) + 1)) as wkno
from your_table
/

Note that wkno comes out as 'W1', 'W2', ... 'W10' which won't sort numerically. There are various workarounds, somne more obvious than opthers, if that's something which botehrs you.

于 2013-04-22T13:44:14.613 回答
0

我认为您可以将功能TO_CHAR和结合起来DECODE,例如:

sql> select decode(to_char(sdate, 'W'),
                   '1', 'w1',
                   '2', 'w2',
                   '3', 'w3',
                   '4', 'w4',
                   '5', 'w5')
       from table1;
于 2013-04-22T12:18:25.190 回答