Reputation: 9
I have table like below. Consider the query
select invoice_mth, inv_amt from table xdetails
where mobile_number=9080808080
data in the table
mobile_number invoice_mth inv_amt
9080808080 2010-10 20
9080808080 2010-11 30
9080808080 2010-12 40
I have to display the data from table like below.
I want invoice months to separate each month and amt separately.
MOBILE_NUMBER inv_m1 inv_m2 inv_m3 amt1 amt2 amt3
------- ----------------------------------------------------------
9080808080 2010-10 2010-11 2010-12 20 30 40
to display the data like above what I have to do?
Upvotes: 0
Views: 3561
Reputation: 167982
If you want a fixed number of columns in the output:
Oracle 11g R2 Schema Setup:
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;
Query 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
| MOBILE_NUMBER | INV_M1 | INV_M2 | INV_M3 | AMT1 | AMT2 | AMT3 |
|---------------|---------|---------|---------|------|------|------|
| 9080808080 | 2010-10 | 2010-11 | 2010-12 | 20 | 30 | 40 |
Upvotes: 0
Reputation: 49082
You could play around with the standard PIVOT query:
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>
Upvotes: 3