加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长百科 > 正文

Oracle行转列/列转行

发布时间:2021-02-25 12:38:10 所属栏目:站长百科 来源:网络整理
导读:1.oracle的pivot函数 原表 行使pivot函数: with temp as( select ‘四川

1.oracle的pivot函数

原表

Oracle行转列/列转行

行使pivot函数:

with temp as(
select ‘四川省‘ nation,‘成都会‘ city,‘第一‘ ranking from dual union all?
select ‘四川省‘ nation,‘绵阳市‘ city,‘第二‘ ranking from dual union all?
select ‘四川省‘ nation,‘德阳市‘ city,‘第三‘ ranking from dual union all?
select ‘四川省‘ nation,‘宜宾市‘ city,‘第四‘ ranking from dual union all?
select ‘湖北省‘ nation,‘武汉市‘ city,‘第一‘ ranking from dual union all?
select ‘湖北省‘ nation,‘宜昌市‘ city,‘第二‘ ranking from dual union all?
select ‘湖北省‘ nation,‘襄阳市‘ city,‘第三‘ ranking from dual?
)
select * from (select nation,city,ranking from temp)pivot (max(city) for ranking in (‘第一‘ as 第一,‘第二‘ AS 第二,‘第三‘ AS 第三,‘第四‘ AS 第四));

Oracle行转列/列转行

声名:pivot(聚合函数?for?列名?in(范例)),个中?in(‘’)?中可以指定别名,in中还可以指定子查询,好比?selectdistinct ranking?from?temp

Oracle行转列/列转行

SELECT * FROM [StudentScores] /*数据源*/
AS P
PIVOT 
(
    SUM(Score/*行转列后 列的值*/) FOR 
    p.Subject/*必要行转列的列*/ IN ([语文],[数学],[英语],[生物]/*列的值*/)
) AS T

Oracle行转列/列转行

?

2.行使max团结decode函数

原表

Oracle行转列/列转行

行使max团结decode函数

with temp as(
select ‘四川省‘ nation,‘第三‘ ranking from dual?
)
select nation,
max(decode(ranking,‘第一‘,‘‘)) as 第一,‘第二‘,‘‘)) as 第二,‘第三‘,‘‘)) as 第三,‘第四‘,‘‘)) as 第四
from temp group by nation;

Oracle行转列/列转行

声名:decode的用法:decode(前提,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)

该函数的寄义如下:

Oracle行转列/列转行

IF 前提=值1 THEN
    RETURN(翻译值1)
ELSIF 前提=值2 THEN
    RETURN(翻译值2)
    ......
ELSIF 前提=值n THEN
    RETURN(翻译值n)
ELSE
    RETURN(缺省值)
END IF

Oracle行转列/列转行

?

3.行使max团结case when 函数

原表

Oracle行转列/列转行

行使max团结case when 函数

select case when grade_id=‘1‘ then ‘一年级‘ when grade_id=‘2‘ then ‘二年级‘ when grade_id=‘5‘ then ‘五年级‘? else null end "年级", max(case when subject_name=‘语文‘? then max_score else 0 end) "语文", max(case when subject_name=‘数学‘? then max_score else 0 end) "数学", max(case when subject_name=‘政治‘? then max_score else 0 end) "政治" from dim_ia_test_ysf group by case when grade_id=‘1‘ then ‘一年级‘ when grade_id=‘2‘ then ‘二年级‘ when grade_id=‘5‘ then ‘五年级‘? else null end

?

?

Oracle行转列/列转行

?

下面是先容列转行要领--列转行

原表

Oracle行转列/列转行

with temp as(
select ‘四川省‘ nation,‘成都会‘ 第一,‘绵阳市‘ 第二,‘德阳市‘ 第三,‘宜宾市‘ 第四? from dual union all?
select ‘湖北省‘ nation,‘武汉市‘ 第一,‘宜昌市‘ 第二,‘襄阳市‘ 第三,‘‘ 第四?? from dual?
)
select nation,name,title from?
temp
unpivot
(name for title in (第一,第二,第三,第四))t

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读