我正在尝试根据表中存在的行动态生成列。
我有一张如下表 -
Name | Sub | Marks
A |Hindi |59
A |Eng |88
A |Maths |68
但是,我需要如下结果 -
Name | Sub | Marks | Sub | Marks | Sub | Marks
A |Hindi |59 |Eng |88 |Maths |68
我无法如何实现同样的目标。非常感谢任何帮助。
答案 0 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE table_name ( Name, Sub, Marks ) AS
SELECT 'A', 'Hindi', 59 FROM DUAL UNION ALL
SELECT 'A', 'Eng', 88 FROM DUAL UNION ALL
SELECT 'A', 'Maths', 68 FROM DUAL;
查询1 :
SELECT *
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY name ORDER BY ROWNUM ) AS rn
FROM table_name t
)
PIVOT (
MAX( Sub ) AS SUB,
MAX( Marks ) AS Marks
FOR rn IN ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )
)
<强> Results 强>:
| NAME | 1_SUB | 1_MARKS | 2_SUB | 2_MARKS | 3_SUB | 3_MARKS | 4_SUB | 4_MARKS | 5_SUB | 5_MARKS | 6_SUB | 6_MARKS | 7_SUB | 7_MARKS | 8_SUB | 8_MARKS | 9_SUB | 9_MARKS | 10_SUB | 10_MARKS |
|------|-------|---------|-------|---------|-------|---------|--------|---------|--------|---------|--------|---------|--------|---------|--------|---------|--------|---------|--------|----------|
| A | Hindi | 59 | Eng | 88 | Maths | 68 | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |