我在Oracle中显示记录时遇到问题。
例如:我将所有记录显示在一行中,如下所示:
id| a | a1 | b | b1
-------------------
1 |400| 1 |410| 3
2 |400| 10 |410| 30
但我需要,记录看起来像那样:
id| code| number
----------------
1 | 400 | 1
1 | 410 | 3
2 | 400 | 10
2 | 410 | 30
也许我应该按功能分组?
请帮帮我。
答案 0 :(得分:1)
这适用于Oracle
select id ,a "code" , a1 "number" from test
union all
select id, b "code",b1 "number" from test
order by id
答案 1 :(得分:0)
使用oracle的UNPIVOT功能,您可以按照以下方式实现此目的
WITH table_ (id, a, a1, b, b1) AS (
SELECT 1, 400, 1, 410, 3 FROM dual UNION ALL
SELECT 3, 300, 4, 310, 5 FROM dual UNION ALL
SELECT 2, 400, 10, 410, 30 from dual)
---------
-- End of data preparation
---------
SELECT id,
CASE
WHEN a1 = 'A' THEN
a
WHEN a1 = 'B' THEN
b
ELSE
NULL
END AS code,
"NUMBER"
FROM table_ unpivot("NUMBER" FOR a1 IN(a1 AS 'A', b1 AS 'B'));
输出:
| ID | CODE | NUMBER |
|----|------|--------|
| 1 | 400 | 1 |
| 1 | 410 | 3 |
| 3 | 300 | 4 |
| 3 | 310 | 5 |
| 2 | 400 | 10 |
| 2 | 410 | 30 |
答案 2 :(得分:0)
可能是unpivot
的语法,
特别是如果你有更多列(c,c1,d,d1 ......):
select id, code, num from test
unpivot ((code, num) for (x, y) in ((a, a1), (b, b1)))