初学者Oracle SQL计数功能多列

时间:2013-04-01 19:28:37

标签: sql oracle function count

我正在阅读有问题和预期输出的练习工作表。最后一个问题证明我很难掌握。任何人都可以帮忙。

问题

创建一个查询以显示员工总数,以及总数, 2005年,2006年,2007年和2008年雇用的员工人数。

预期输出格式

Total 2005 2006 2007 2008
107   29   24   19   11

以下是我尝试使用单独查询获取结果

TO_CHAR(hire_date,'YYYY')
SELECT COUNT(employee_id) AS "Total"
FROM employees;

SELECT COUNT(employee_id) AS "2005"
FROM employees
WHERE TO_CHAR(hire_date,'YYYY') LIKE '2005' GROUP BY TO_CHAR(hire_date,'YYYY') ;

SELECT COUNT(employee_id) AS "2006"
FROM employees
WHERE TO_CHAR(hire_date,'YYYY') LIKE '2006' GROUP BY TO_CHAR(hire_date,'YYYY') ;

SELECT COUNT(employee_id) AS "2007"
FROM employees
WHERE TO_CHAR(hire_date,'YYYY') LIKE '2007' GROUP BY TO_CHAR(hire_date,'YYYY') ;

SELECT COUNT(employee_id) AS "2008"
FROM employees
WHERE TO_CHAR(hire_date,'YYYY') LIKE '2008' GROUP BY TO_CHAR(hire_date,'YYYY') ;

非常感谢任何以一个查询产生结果的帮助。

2 个答案:

答案 0 :(得分:2)

要将这些放入列中,请使用条件聚合:

select count(*) as Total,
       sum(case when to_char(hire_date, 'yyyy') = '2005' then 1 else 0 end) as "2005",
       sum(case when to_char(hire_date, 'yyyy') = '2006' then 1 else 0 end) as "2006",
       sum(case when to_char(hire_date, 'yyyy') = '2007' then 1 else 0 end) as "2007",
       sum(case when to_char(hire_date, 'yyyy') = '2008' then 1 else 0 end) as "2008"
from employees
where to_char(hire_date, 'yyyy') in ('2005', 2006', '2007', '2008')

答案 1 :(得分:1)

您正在尝试 pivot 数据,因此您可以使用现有查询,但在聚合内添加CASE表达式:

SELECT COUNT(employee_id) AS "Total",
    sum(case when TO_CHAR(hire_date,'YYYY') = '2005' then 1 else 0 end) "2005",
    sum(case when TO_CHAR(hire_date,'YYYY') = '2006' then 1 else 0 end) "2006",
    sum(case when TO_CHAR(hire_date,'YYYY') = '2007' then 1 else 0 end) "2007",
    sum(case when TO_CHAR(hire_date,'YYYY') = '2008' then 1 else 0 end) "2008"
FROM employees;

根据您的Oracle版本,您可以使用PIVOT函数:

select *
from
(
  select count(*) over() Total,
    TO_CHAR(hire_date,'YYYY') Year
  from employees
) 
pivot
(
    count(Year)
    for Year in ('2005', '2006', '2007', '2008')
) 

请参阅Demo of both queries