最近刚开始学习sql语法,看到分组函数章节,被一道课后习题难住了,实在是想不到好的方法
问题:创建一个查询,显示员工总数以及其中在1980年、1981年、1982年聘用的员工
表就是emp表
要求输出像这样的结果
列名: total | 1980 | 1981 | 1982
查询结果: 14 1 10 1
我自己想到的只能做到这样
select count(*),to_char(hiredate,'yy') from emp where to_char(hiredate,'yy') in ('80','81','82')
group by to_char(hiredate,'yy');
COUNT(*) TO
---------- --
10 81
1 82
1 80
不知道各位有没有好的实现方法,因为下一章才学子查询,所以这里应该不用子查询来解(或者是我想多了,反正不用子查询就是了。。。。)
------解决方案--------------------
行转列问题
select count(*),
count(case to_char(hiredate,'yyyy') when '1980' then 1 end) "1980",
count(case to_char(hiredate 'yyyy') when '1981' then 1 end )"1981",
count(case to_char(hiredate,'yyyy') when '1982' then 1 end) "1982"
from emp
------解决方案--------------------
total怎么会是14,应该是12 吧,两种方法如下:
--decode
select sum(decode(to_char(hiredate, 'yyyy'),
'1980',
1,
'1981',
1,
'1982',
1)) "total",
sum(decode(to_char(hiredate, 'yyyy'), '1980', 1)) "1980",
sum(decode(to_char(hiredate, 'yyyy'), '1981', 1)) "1981",
sum(decode(to_char(hiredate, 'yyyy'), '1982', 1)) "1982"
from scott.emp;
--case when
select sum(case to_char(hiredate, 'yyyy')
when '1980' then
1
when '1981' then
1
when '1982' then
1
end) "total",
sum(case to_char(hiredate, 'yyyy')
when '1980' then
1
end) "1980",