oracle的行列转换,怎么实现?
发布网友
发布时间:2022-04-09 03:39
我来回答
共4个回答
热心网友
时间:2022-04-09 05:08
--行转列的3种方法,参考
--http: / / blog.sina.com.cn/s/blog_475839a50100s2q3.html
--1. UNION ALL
--适用范围:8i,9i,10g及以后版本
with tmp as(
select 123 as a, 456 as b, 789 as c from al)
SELECT a 新列名 FROM tmp
UNION ALL
SELECT b FROM tmp
UNION ALL
SELECT c FROM tmp
--若空行不需要转换,只需加一个where条件,
--WHERE COLUMN IS NOT NULL 即可。
--2. MODEL
--适用范围:10g及以后
with tmp as(
select 123 as a, 456 as b, 789 as c from al)
SELECT v 新列名 FROM tmp
MODEL
RETURN UPDATED ROWS
DIMENSION BY (0 AS n)
MEASURES ('xx' AS cn,'yyy' AS v,a,b,c)
RULES UPSERT ALL(
v[1] = a[0],
v[2] = b[0],
v[3] = c[0]
)
--3. COLLECTION
--适用范围:8i,9i,10g及以后版本
--要创建一个对象和一个集合:
CREATE OR REPLACE TYPE v_type AS OBJECT(v VARCHAR2(100));
CREATE OR REPLACE TYPE v_varr AS VARRAY(8) OF v_type;
with tmp as(
select 123 as a, 456 as b, 789 as c from al)
SELECT t.v AS 新列名
FROM tmp,
TABLE(v_varr(v_type(tmp.a),v_type(tmp.b),v_type(tmp.c))) t;
热心网友
时间:2022-04-09 06:26
select 123 from table_name
union
select 456 from table_name
union
select 789 from table_name
热心网友
时间:2022-04-09 08:01
你这种的话 果断用递归方式
以前做过个类似的 SQL给你贴出来 适当改一下
-------------------
1.创建测试表
create table zxt_test
( id varchar(10),
ivalue varchar(20),
iname varchar(20)
)
commit;
-----------
2.插入测试语句
insert into zxt_test values('1','aa','x'),('2','bb','x'),('3','bb','x'),('1','bb','y'),('2','bb','y'),('3','bb','y');
commit;
---------------
3.查看数据
select * from zxt_test;
1 'aa' 'x'
2 'bb' 'x'
3 'bb' 'x'
1 'bb' 'y'
2 'bb' 'y'
3 'bb' 'y'
----------------
4.with 的写法!
with
s as (
select row_number()over(partition by iname order by id) id1,
row_number()over(partition by iname order by id) id2,
ivalue,iname from zxt_test
)
,
t(iname,id1,id2,ivalue) as
(
select iname,id1,id2,cast(ivalue as varchar(100)) from s where id1 =1 and id2=1
union all
select t.iname,t.id1+1,t.id2,cast(s.ivalue||','||t.ivalue as varchar(100))
from s, t
where s.id2=t.id1+1 and t.iname = s.iname
)
select iname,ivalue from t where t.id1= (select max(id1) from s where s.iname = t.iname);
5.结果如下:
'x' 'bb,bb,aa'
'y' 'bb,bb,bb'
热心网友
时间:2022-04-09 09:52
jkj_fj正确