And*_*anu 1 sql oracle group-by
使用ORACLE SQL.
我有一个表' Employees'有一个属性' hire_date'.我的任务(书籍练习)是写一个SELECT能告诉我1995年,1996年,1997年和1998年雇用了多少员工的任务.
就像是:
TOTAL 1995 1996 1997 1998
-----------------------------------------
20 4 5 29 2
Run Code Online (Sandbox Code Playgroud)
单独计算每年的员工数量,例如:
SELECT
COUNT(*),
FROM
employees e
WHERE
e.hire_date like '%95'
Run Code Online (Sandbox Code Playgroud)
但是当我必须以所需格式"聚合"数据时,我遇到了困难.有什么建议 ?
我假设您的hire_date是varchar2,因为您在示例中执行了"like"子句.
一个简单的桌子每年会有一排吗?
如果是这样,请在Oracle中尝试:
select case grouping(hire_date)
when 0 then hire_date
else 'TOTAL'
end hire_date,
count(hire_date) as count_hire_date
from employees
group by rollup(hire_date);
Run Code Online (Sandbox Code Playgroud)
这应该是这样的:
hire_date count_hire_date
1995 10
1996 20
1997 30
TOTAL 60
Run Code Online (Sandbox Code Playgroud)
如果您确实需要将结果转换为您在问题中显示的内容,那么如果您知道运行查询之前的不同年份,则可以执行以下操作.例如,如果你知道你的表中只有1995,1996和1997,那么你可以使用这个来转动结果:
SELECT
MAX(CASE WHEN hire_date = 'TOTAL' THEN ilv.count_hire_date END) total,
MAX(CASE WHEN hire_date = '1995' THEN ilv.count_hire_date END) count_1995,
MAX(CASE WHEN hire_date = '1996' THEN ilv.count_hire_date END) count_1996,
MAX(CASE WHEN hire_date = '1997' THEN ilv.count_hire_date END) count_1997
from (
select case grouping(hire_date)
when 0 then hire_date
else 'TOTAL'
end hire_date,
count(hire_date) as count_hire_date
from employees
group by rollup(hire_date)
) ilv;
Run Code Online (Sandbox Code Playgroud)
这有一个明显的缺点,你需要为每个可能的年份在主select语句中添加一个新子句.