当前位置:首页>开发>正文

oracle中如何写SQL实现行列转换 oracle的行列转换,怎么实现

2024-01-03 10:16:53 互联网 未知 开发

 oracle中如何写SQL实现行列转换 oracle的行列转换,怎么实现

oracle中如何写SQL实现行列转换?

问下是不是课程只有语文 ,数学,英语没有别的?
如果是的话那么:
数据库是sqlserver的话执行:
select b.stu_name,
max(case a.subject when 语文 then a.grade else end) as 语文,
max(case a.subject when 数学 then a.grade else end) as 数学,
max(case a.subject when 英语 then a.grade else end) as 英语
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name
数据库为oralce的话执行
select b.stu_name,
max(case a.subject when 语文 then to_char(a.grade) else end) as 语文,
max(case a.subject when 数学 then to_char(a.grade) else end) as 数学,
max(case a.subject when 英语 then to_char(a.grade) else end) as 英语
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name

oracle的行列转换,怎么实现?

--行转列的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 dual)
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 dual)
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 dual)
SELECT t.v AS 新列名
FROM tmp,
TABLE(v_varr(v_type(tmp.a),v_type(tmp.b),v_type(tmp.c))) t

最新文章