想要在两列上透视数据

时间:2014-07-14 08:17:46

标签: pivot

我有如下数据。

Region  Transactions    Production  Value
EAST    Sales             LUX        1000
EAST    Sales             Cinthol    1500
EAST    Purchases         LUX        1000
EAST    Purchases         Cinthol    1500
NORTH   Sales             LUX        3000
NORTH   Sales             Cinthol    3500
NORTH   Purchases         LUX        3000
NORTH   Purchases         Cinthol    3500
SOUTH   Sales             LUX        4000
SOUTH   Sales             Cinthol    4500
SOUTH   Purchases         LUX        4000
SOUTH   Purchases         Cinthol    4500
WEST    Sales             LUX        2000
WEST    Sales             Cinthol    2500
WEST    Purchases         LUX        2000
WEST    Purchases         Cinthol    2500

我在上表格式的表中有近1,00,000行的数据。

因此,通过查询我想要以下格式的数据。

             LUX                CINTHOL 
Region  SALES   PURCHASES   SALES   PURCHASES
EAST    1000    1000    1500    1500
WEST    2000    2000    2500    2500
NORTH   3000    3000    3500    3500
SOUTH   4000    4000    4500    4500

1 个答案:

答案 0 :(得分:-1)

如果Oracle 11g中的RDBMS您可以使用PIVOT语句:11g-pivot

WITH p1 AS
  (
     SELECT region, SALES_SUM_VALUE, PURCHASES_SUM_VALUE
       FROM
      (
         SELECT *
           FROM
          (
             SELECT *
               FROM special_data
              WHERE production = 'LUX'
          )
          PIVOT( SUM(value) AS SUM_VALUE FOR(transactions) IN('Sales' AS Sales, 'Purchases' AS Purchases))
      )
  )
  , p2 AS
  (
     SELECT region, SALES_SUM_VALUE, PURCHASES_SUM_VALUE
       FROM
      (
         SELECT *
           FROM
          (
             SELECT *
               FROM special_data
              WHERE production = 'Cinthol'
          )
          PIVOT( SUM(value) AS SUM_VALUE FOR(transactions) IN('Sales' AS Sales, 'Purchases' AS Purchases))
      )
  )
 SELECT p1.region, p1.SALES_SUM_VALUE LUX_SALES, p1.PURCHASES_SUM_VALUE LUX_PURCHASES, p2.SALES_SUM_VALUE Cinthol_SALES, p2.PURCHASES_SUM_VALUE Cinthol_PURCHASES
   FROM p1, p2
  WHERE p1.region = p2.region

我为你准备了一些小提琴:SQL FIDDLE