oracle横着数据竖起来显示 Case When语句
今天去面试,碰到一个题目。大致如下:
year month money(money自己瞎写的,忘记了题目中的单词了,当然不影响这个题目)
1991 1 1.1
1991 2 1.2
1991 2 1.3
1991 2 1.4
1992 2 2.1
1992 2 2.2
1992 2 2.3
1992 2 2.4
要求把 数据 横着显示,写一段sql实现:
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
因为本人才疏学浅,没写出来,回来查了下。原来是case when 语句。
故写下来,分享下(表名字就随便取一个了)。
create table bill(
b_year varchar2(4),
b_month varchar2(2),
money varchar2(10) -- 这里为了写起来方便,就写varchar2了
);
insert into billvalues('1991','1','1.1');
insert into billvalues('1991','2','1.2');
insert into billvalues('1991','3','1.3');
insert into billvalues('1991','4','1.4');
insert into billvalues('1992','1','2.1');
insert into billvalues('1992','2','2.2');
insert into billvalues('1992','3','2.3');
insert into billvalues('1992','4','2.4');
下面是一种实现方式:
select b_year as year,
max(case b_month when '1' money, else '0' end) m1,
max(case b_month when '2' money, else '0' end) m2,
max(case b_month when '3' money, else '0' end) m3,
max(case b_month when '4' money, else '0' end) m4
from bill group by b_year;
结果:
case?when?oracle case?when oracle
[解决办法]
是不是数据错了? 一年1、2、3、4月份 复制了没改的
如果月份是确定的 用decode函数也可以
如果不确定 那要用动态sql了 比较基本的列转行
[解决办法]
学习了,很不错
[解决办法]
比较不错 的,但是 我觉得 么必要 用 那个max 函数吧 ,
select b_year as year,
case b_month
when '1' then
m1
when '2' then
m2
when '3' then
m3
when '4' then
m4
end
from bill grob_monthup by b_year;
我觉得 这样 更好些 ,我楼主 上面的 哪儿 月份 好像是 写错了,但是 插入的 时候 是 对的 数据,
那么那个 max 就没什么 用了 ,加了 性能 就 不好 了。
[解决办法]
用行列转换decode()函数
select b_year,max(M1) M1,max(M2) M2,max(M3) M3,max(M4) M4 from
(select b_year,decode(b_month,1,money,'')M1,
decode(b_month,2,money,'')M2,
decode(b_month,3,money,'')M3,
decode(b_month,4,money,'')M4
from bill) group by b_year;
[解决办法]
你试一下 我执行了没问题
[解决办法]
这个SQL明显是错误的。。。
[解决办法]
这个貌似没有什么实际的意义!!
[解决办法]
select a.b_year,
SUM(decode(a.b_month, 1, a.money)) M1,
SUM(decode(a.b_month, 2, a.money)) M2,
SUM(decode(a.b_month, 3, a.money)) M3,
SUM(decode(a.b_month, 4, a.money)) M4
from bill a
GROUP BY A.B_YEAR
