1

我想知道如何从数据库中检索数据,所以我会有两列。这是我想要完成的一个例子:

EMPLOYEE_Total | YEAR_HIRED
----------------------------
5                  1995

(特定年份雇用的员工人数)

不幸的是,现在我遇到了一些麻烦,因此每年只能获得一排。

在此处输入图像描述

这是我的查询。你能帮我么?谢谢。!

 SELECT COUNT(EMPLOYEE_ID) AS EMPLOYEE_TOTAL, TO_CHAR(HIRE_DATE, 'YYYY') AS YEAR_HIRED 
 FROM EMPLOYEES
 WHERE hire_date 
 BETWEEN '01-JAN-1995' AND '31-DEC-1998'
 GROUP BY HIRE_DATE
 ORDER BY HIRE_DATE
4

3 回答 3

1

您当前的查询非常接近您真正想要的。你会想要改变你GROUP BY使用的TO_CHAR(HIRE_DATE, 'YYYY'),这会导致grouping to be by year instead of thehire_date`有月份,年份等:

SELECT COUNT(EMPLOYEE_ID) AS EMPLOYEE_TOTAL, 
  TO_CHAR(HIRE_DATE, 'YYYY') AS YEAR_HIRED 
FROM EMPLOYEES
WHERE hire_date BETWEEN '01-JAN-1995' AND '31-DEC-1998'
GROUP BY TO_CHAR(HIRE_DATE, 'YYYY')
ORDER BY YEAR_HIRED
于 2013-02-25T21:27:32.827 回答
1

你想改变你的group byand order by

 SELECT COUNT(EMPLOYEE_ID) AS EMPLOYEE_TOTAL, TO_CHAR(HIRE_DATE, 'YYYY') AS YEAR_HIRED 
 FROM EMPLOYEES
 WHERE hire_date 
 BETWEEN '01-JAN-1995' AND '31-DEC-1998'
 GROUP BY to_char(HIRE_DATE, 'YYYY')
 ORDER BY to_char(HIRE_DATE, 'YYYY')

艺术,以下作品:

with emp as (select sysdate - 31*365 as hiredate from dual)
SELECT count(*), to_char(hiredate, 'YYYY') hiredate 
  FROM emp
 WHERE hiredate BETWEEN '01-JAN-1980' AND '01-JAN-1983'
GROUP BY to_char(hiredate, 'YYYY')
ORDER BY to_char(hiredate, 'YYYY')

您可以在SQL Fiddle上查看。

于 2013-02-25T21:26:55.117 回答
1

现有 Oracle 表的示例 - 已测试:

SELECT count(*), to_char(hiredate, 'YYYY') hiredate 
  FROM scott.emp
 WHERE hiredate BETWEEN '01-JAN-1980' AND '01-JAN-1983'
GROUP BY to_char(hiredate, 'YYYY')
ORDER BY to_char(hiredate, 'YYYY')
/

输出:ORA-01481:无效的数字格式模型

这将起作用并通过以下任何顺序给出相同的结果:

SELECT count(*), to_char(hiredate, 'YYYY') hiredate 
  FROM scott.emp
 WHERE hiredate BETWEEN '01-JAN-1980' AND '01-JAN-1983'
GROUP BY to_char(hiredate, 'YYYY')
--ORDER BY to_date(hiredate, 'YYYY')
-- ORDER BY hiredate
 ORDER BY 2
/

COUNT(*)    HIREDATE
-----------------------
1          1980
10         1981
1          1982
于 2013-02-25T21:55:51.337 回答