我有一个数据库,其中包含如下表1所示的样本数据。如何编写SQL查询以表2或表3格式显示它们?
Table 1 Table 2 Date | Value Year | Week | Total Value | % Change ------------+------- ------+-----+--|---------------|---------- 19/12/2011 | 60 2012 | 1 | 295 | 656.41% 20/12/2011 | 49 2012 | 0 | 39 | -80.98% 21/12/2011 | 42 2012 | 52 | 205 | -41.76% 22/12/2011 | 57 2011 | 51 | 352 | 23/12/2011 | 88 24/12/2011 | 18 Table 3 25/12/2011 | 38 Year | Week | SUM1 | Year | Week | SUM2 | % Change 26/12/2011 | 16 ------+--------+--------+--------+--------+--------+----------- 27/12/2011 | 66 2012 | 1 | 295 | 2012 | 0 | 39 | 656.41% 28/12/2011 | 21 2012 | 0 | 39 | 2011 | 52 | 205 | -80.98% 29/12/2011 | 79 2011 | 52 | 205 | 2011 | 51 | 352 | -41.76% 30/12/2011 | 7 2011 | 51 | 352 | 31/12/2011 | 16 01/01/2012 | 39 02/01/2012 | 17 03/01/2012 | 86 04/01/2012 | 55 05/01/2012 | 82 06/01/2012 | 0 07/01/2012 | 9 08/01/2012 | 46
答案 0 :(得分:1)
我的偏好是运行1个查询将表1汇总到年/周级别,然后根据您的环境用另一种语言执行“%change”。但是,如果您真的需要一个只有SQL的解决方案,那么您可以这样做。
create table t1 as
select year(Date) as year, week(Date) as week, sum(Value) as totalvalue
from table1
group by year(Date) as year, week(Date) as week
order by Date desc
;
select a.year, a.month, a.totalvalue,
(a.totalvalue-b.totalvalue)/b.totalvalue as pct_change
from (
select year, month, totalvalue,
case when week>1 then week-1 else 52 end as prevweek,
case when week>1 then year else year-1 end as prevyear
from t1
) a
left outer join t1 b
on a.prevweek=b.week and a.prevyear =b.year
;