PIVOT查询中的行和

时间:2017-04-26 08:51:16

标签: oracle

请帮助我,我正在尝试创建枢轴但不成功。

查询

select 
t.g_no,
t.sz,
t.DT,
t.Qty
from gp123 t

结果

 4480   46  4/24/2017   30
 4480   42  4/24/2017   28
 4480   40  4/24/2017   37
 4480   44  4/24/2017   26
 4480   50  4/24/2017   17
 4480   48  4/24/2017   2

必填结果

  Gate Pass No.   Date      40  42  44  46  48  50     Total
  4480           24-Apr-17  37  28  26  30  2   17       140
  4500           25-Apr-17  187 140 155 127 99  85       793
  4537           25-Apr-17  141 97  139 172 141 159      849
  4538           26-Apr-17  90  141 122 148 172 151      824
  4542           26-Apr-17  1   60  118 63  32  3        277

2 个答案:

答案 0 :(得分:2)

使用SUM() OVER ()分析函数获取总数,然后使用PIVOT将行转换为列:

SELECT *
FROM   ( SELECT g_no AS "Gate Pass No.",
                sz,
                DT AS "Date",
                Qty,
                SUM( qty ) OVER ( PARTITION BY g_no, DT ) AS Total
          FROM  gp123
       )
PIVOT  ( SUM( qty ) FOR sz IN ( 40, 42, 44, 46, 48, 50 ) )

答案 1 :(得分:0)

......或简单地说:

select g_no, dt, "40", "42", "44", "46", "48", "50",
       "40" + "42" + "44" + "46" + "48" + "50" total
  from gp123 t
  pivot (sum(qty) for sz in (40, 42, 44, 46, 48, 50));