SQL:透视查询数据的方式

时间:2016-08-11 15:34:57

标签: sql oracle pivot

我有一张桌子如下图所示。我想查询并将行数据显示为列

Customer  MetricName MetricValue    Date
 A          Upload    2          10-AUG-2007
 A          Download  2          10-AUG-2007
 A          Storage   100        10-AUG-2007
 A          Storage   110        11-AUG-2007
 B          Storage   200        11-AUG-2007
 A          Upload    2          12-AUG-2007
 A          Download  2          12-AUG-2007
 B          Upload    2          10-AUG-2007
 B          Download  2          10-AUG-2007

上周使用

下载 - 一周内所有下载量的总和  存储 - 本周最高价值

 Customer  Download  Upload   Storage
   A          4        4        110
   B          2        2        200

如何使用Pivot或其他方法实现此目的

1 个答案:

答案 0 :(得分:0)

像这样...... PIVOT需要将相同的聚合函数全部应用于列;旧的"手册"使用case表达式的旋转方式更灵活(如下所示)。我不确定你的意思是什么?#34;周" - 我只是把它放在WHERE条款中。另外,不要使用像DATE这样的保留字来表示列(或表)名称,你不能直接这样做,你不应该用唯一可能的方式(使用双引号) - 它&# 39;练习很差。我将列名Date更改为dt

with 
     input_data ( customer, metricname, metricvalue, dt ) AS (
       select 'A', 'Upload'  ,  2   , to_date('10-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'A', 'Download',  2   , to_date('10-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'A', 'Storage' ,  100 , to_date('10-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'A', 'Storage' ,  110 , to_date('11-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'B', 'Storage' ,  200 , to_date('11-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'A', 'Upload'  ,  2   , to_date('12-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'A', 'Download',  2   , to_date('12-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'B', 'Upload'  ,  2   , to_date('10-AUG-2007', 'dd-MON-yyyy') from dual union all
       select 'B', 'Download',  2   , to_date('10-AUG-2007', 'dd-MON-yyyy') from dual
     )
select   customer,
         sum( case when metricname = 'Upload'   then metricvalue end) as upload,
         sum( case when metricname = 'Download' then metricvalue end) as download,
         max( case when metricname = 'Storage'  then metricvalue end) as storage
from     input_data
where    dt between to_date('09-AUG-2007', 'dd-MON-yyyy') and 
                                               to_date('15-AUG-2007', 'dd-MON-yyyy')
group by customer
order by customer
;

CUSTOMER     UPLOAD   DOWNLOAD    STORAGE
-------- ---------- ---------- ----------
A                 4          4        110
B                 2          2        200