将多行PIVOT分配到列中

时间:2015-03-17 07:59:49

标签: sql oracle oracle11g pivot

我有下面的表格。考虑查询

select invoice_mth, inv_amt from table xdetails
 where mobile_number=9080808080

表中的数据

mobile_number   invoice_mth  inv_amt
 9080808080     2010-10        20
 9080808080     2010-11        30
 9080808080     2010-12        40

我必须显示如下表格中的数据。

我希望发票月份每个月分开并单独分开。

MOBILE_NUMBER   inv_m1   inv_m2    inv_m3   amt1    amt2    amt3
------- ----------------------------------------------------------
 9080808080    2010-10   2010-11   2010-12   20       30      40

显示上面的数据我必须做什么?

2 个答案:

答案 0 :(得分:2)

您可以使用标准 PIVOT 查询:

SQL> SELECT * FROM t;

MOBILE_NUMBER INVOICE    INV_AMT
------------- ------- ----------
   9080808080 2010-10         20
   9080808080 2010-11         30
   9080808080 2010-12         40

SQL>
SQL> SELECT *
  2  FROM
  3    (SELECT mobile_number, invoice_mth, inv_amt FROM t
  4    ) PIVOT (MIN(invoice_mth) AS inv_mth,
  5             SUM(inv_amt) AS inv_amt
  6             FOR (invoice_mth) IN ('2010-10' AS m1, '2010-11' AS m2, '2010-12' AS m3))
  7  ORDER BY mobile_number;

MOBILE_NUMBER M1_INV_ M1_INV_AMT M2_INV_ M2_INV_AMT M3_INV_ M3_INV_AMT
------------- ------- ---------- ------- ---------- ------- ----------
   9080808080 2010-10         20 2010-11         30 2010-12         40

SQL>

答案 1 :(得分:0)

如果您想在输出中使用固定数量的列:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TABLE_NAME ( mobile_number, invoice_mth, inv_amt ) AS
          SELECT 9080808080, '2010-10', 20 FROM DUAL
UNION ALL SELECT 9080808080, '2010-11', 30 FROM DUAL
UNION ALL SELECT 9080808080, '2010-12', 40 FROM DUAL;

查询1

SELECT mobile_number,
       MAX( CASE RN WHEN 1 THEN invoice_mth END ) AS inv_m1,
       MAX( CASE RN WHEN 2 THEN invoice_mth END ) AS inv_m2,
       MAX( CASE RN WHEN 3 THEN invoice_mth END ) AS inv_m3,
       MAX( CASE RN WHEN 1 THEN inv_amt END ) AS amt1,
       MAX( CASE RN WHEN 2 THEN inv_amt END ) AS amt2,
       MAX( CASE RN WHEN 3 THEN inv_amt END ) AS amt3
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY mobile_number ORDER BY invoice_mth ASC ) AS rn
  FROM   TABLE_NAME t
)
GROUP BY mobile_number

<强> Results

| MOBILE_NUMBER |  INV_M1 |  INV_M2 |  INV_M3 | AMT1 | AMT2 | AMT3 |
|---------------|---------|---------|---------|------|------|------|
|    9080808080 | 2010-10 | 2010-11 | 2010-12 |   20 |   30 |   40 |