使用ORACLE SQL。
我有一个表'Employees‘,其中一个属性是'hire_date’。我的任务(书本练习)是写一个SELECT,告诉我1995年、1996年、1997年和1998年雇佣了多少员工。
类似于:
TOTAL 1995 1996 1997 1998
-----------------------------------------
20 4 5 29 2单独计算每年的雇员人数很容易,例如:
SELECT
COUNT(*),
FROM
employees e
WHERE
e.hire_date like '%95'但是,当我必须以所需的格式‘聚合’数据时,我遇到了困难。有什么建议吗?
发布于 2010-11-17 21:01:34
我假设您的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);这应该会给出一些类似的东西:
hire_date count_hire_date
1995 10
1996 20
1997 30
TOTAL 60如果您确实需要将结果转换为您在问题中所显示的内容,那么您可以在运行查询之前知道不同的年份集的情况下执行以下操作。因此,例如,如果您知道您的表中只有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;这有一个明显的缺点,就是您需要为每个可能的年份在主select语句中添加一个新的子句。
发布于 2010-11-17 21:06:06
语法不直观。这利用了剪切粘贴代码:
SQL> select
2 sum(case when to_char(hiredate, 'YYYY') = '1980' then 1 else 0 end) as "1980"
3 , sum(case when to_char(hiredate, 'YYYY') = '1981' then 1 else 0 end) as "1981"
4 , sum(case when to_char(hiredate, 'YYYY') = '1982' then 1 else 0 end) as "1982"
5 , sum(case when to_char(hiredate, 'YYYY') = '1983' then 1 else 0 end) as "1983"
6 , sum(case when to_char(hiredate, 'YYYY') = '1987' then 1 else 0 end) as "1987"
7 , count(*) as total
8 from emp
9 /
1980 1981 1982 1983 1987 TOTAL
---------- ---------- ---------- ---------- ---------- ----------
1 10 1 0 2 20
Elapsed: 00:00:00.00
SQL>发布于 2010-11-17 20:54:56
下面是我如何在MS SQL中做这件事--它在Oracle中将是类似的,但我不想尝试给你Oracle代码,因为我通常不会写它。这只是为了给你一个基本的框架。
Select
Year(e.hire_date),
Count(1)
From
employees e
Group By
Year(e.hire_date)https://stackoverflow.com/questions/4204492
复制相似问题