在这个转的帖子中,又一次我引了这种类型的帖子了,其实挺简单的,反正记载下吧.
SQL如何按时间段取值
下面这张表中(table A),我如何以日期(星期)为段取值,还请赐教,谢谢
table A:
name date qty
--------------------------------------------------------------------
A91111 2010/01/4 10
A92222 2010/02/7 20
A93333 2010/03/5 30
A94444 2010/03/16 40
我现在只了解以上信息,现在需要以每个星期7天取值,如 2010/01/4~2010/01/11为第一周,
那么其这个范围的name A91111,A92222,都在这个范围内,数量就为30,以第二周计算2010/01/11~2010/01/18,以次类推,
table B:
name 第一周qty total 第二周qty total 第三周qty total 第四周qty total 第五周qty total 第六周以上qty total
---------------------------------------------------------------------------------------------------------------------------------------------------------------
A91111 10
A92222 20
A93333 30
A94444 40
Solution:
with t_a as
(
select 'A91111' name, to_date('2010/01/04', 'YYYY/MM/DD') dt, 10 qty from dual
union all
select 'A92222' name, to_date('2010/02/07', 'YYYY/MM/DD') dt,20 qty from dual
union all
select 'A93333' name, to_date('2010/03/05', 'YYYY/MM/DD') dt,30 qty from dual
union all
select 'A94444' name, to_date('2010/03/16', 'YYYY/MM/DD') dt,40 qty from dual
),
t_aa as
(
select name, dt, qty, floor((dt - to_date('2010/01/04', 'YYYY/MM/DD'))/7 + 1) wk from t_a
)
select name, dt, qty,
decode (wk, 1, qty, 0) wk1,
decode (wk, 2, qty, 0) wk2,
decode (wk, 3, qty, 0) wk3,
decode (wk, 4, qty, 0) wk4,
decode (wk, 5, qty, 0) wk5,
decode (sign(wk-5), 1, qty, 0) wk6
from t_aa