问题
want to split the columns in result of query dynamically, how can i? i have three tables and joined them.to get the required columns.
select distinct t1.sal,t1.cat,t2.id,t3.shop
from t_table1 t1,
t_table2 t2,
t_table3 t3,
where t1.sno=t2.sno AND
t2.cat=t3.cat
t3.dept_no=t3.dept_no
**output:**
t1.sal t1.cat t2.id t3.shop
1900 34R5 10 dense
1900 34r5 10 SVM
1900 34r5 10 bpo
2345 3ER4 11 kpo
2345 3ER4 11 infra
12345 34F4 12 const
**desired output:**
t1.sal t1.cat t1.tin t2.id t3.shop_1 t3.shop_2 t3.shop_3
1900 34r5 23456 10 dense svm bpo
2345 3er4 6543 11 kpo infra null
12345 34f4 34556 12 const null null
回答1:
Use a PIVOT
and the ROW_NUMBER
analytic function:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE your_query_result (sal, cat, id, shop ) AS
SELECT 1900, '34R5', 10, 'dense' FROM DUAL UNION ALL
SELECT 1900, '34r5', 10, 'SVM' FROM DUAL UNION ALL
SELECT 1900, '34r5', 10, 'bpo' FROM DUAL UNION ALL
SELECT 2345, '3ER4', 11, 'kpo' FROM DUAL UNION ALL
SELECT 2345, '3ER4', 11, 'infra' FROM DUAL UNION ALL
SELECT 12345, '34F4', 12, 'const' FROM DUAL;
Query 1:
SELECT sal,
cat,
id,
"1_SHOP" AS shop_1,
"2_SHOP" AS shop_2,
"3_SHOP" AS shop_3
FROM (
SELECT r.*,
ROW_NUMBER() OVER (
PARTITION BY sal, cat, id
ORDER BY shop
) AS rn
FROM (
SELECT * FROM your_query_result
) r
)
PIVOT (
MAX( shop ) AS shop
FOR rn IN ( 1, 2, 3 )
)
Results:
| SAL | CAT | ID | SHOP_1 | SHOP_2 | SHOP_3 |
|-------|------|----|--------|--------|--------|
| 1900 | 34R5 | 10 | dense | (null) | (null) |
| 1900 | 34r5 | 10 | SVM | bpo | (null) |
| 2345 | 3ER4 | 11 | infra | kpo | (null) |
| 12345 | 34F4 | 12 | const | (null) | (null) |
If you want the first and second rows on the same line then just change the CAT
column to be in lower-case before generating the ROW_NUMBER
and PIVOT
ing.
来源:https://stackoverflow.com/questions/51055826/how-to-divide-the-columns-in-result-of-query-in-oracle-database