2012-04-19 79 views
0

我有一个数据库,其中包含表1所示的示例数据。如何编写SQL查询以表2或表3格式显示它们?用于显示%更改的SQL查询

 
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 
+1

为什么要以另一个表的格式显示数据?为什么不只是查看/访问该表? – SpeedCrazy 2012-04-19 03:29:08

+0

@SpeedCrazy - 可能他想显示计算? – 2012-04-19 03:34:34

+0

@louis - 你如何计算%变化?你比较哪些数字? – 2012-04-19 03:36:12

回答

1

我希望运行1个查询来将表1聚合到年/周水平,然后根据您的环境在另一种语言中执行“%更改”。但是,如果您确实需要一个纯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 
; 
+0

是的,我宁愿在SQL之外进行pct_change,但是我的麻烦在于我对SQL的不了解!我从来没有在SQL中遇到过“CASE”,我会再读一点,并将其适用于我的解决方案! – 2012-04-19 06:17:24