一个SQL查询计算更年轻或相同年龄的人

时间:2013-12-30 16:41:54

标签: sql db2

我的SQL查询有问题。我必须计算有多少其他员工的年龄小于或等于当前行中的员工。我尝试了几种方法,但没有一种方法可行。它在DB2中给出了一个错误:“标量全查询,SELECT INTO语句或VALUES INTO语句的结果不止一行。”。这是我的疑问:

SELECT e.EMPNO, e.BIRTHDATE, YEAR(CURRENT_DATE - e.BIRTHDATE) AS AGE, COUNT(EMPNO) AS COUNT
FROM EMPLOYEE e
WHERE YEAR(CURRENT_DATE - e.BIRTHDATE) >=
(SELECT YEAR(CURRENT_DATE - BIRTHDATE) FROM EMPLOYEE
WHERE EMPNO > e.EMPNO)
GROUP BY EMPNO, e.BIRTHDATE

2 个答案:

答案 0 :(得分:1)

此查询的问题是SELECT YEAR(CURRENT_DATE - BIRTHDATE) FROM EMPLOYEE WHERE EMPNO > e.EMPNO子查询返回多行。

您可以使用联接解决此问题,如下所示:

SELECT
    e.EMPNO
,   e.BIRTHDATE
,   YEAR(CURRENT_DATE - e.BIRTHDATE) AS AGE
,   COUNT(other.EMPNO) AS COUNT
FROM EMPLOYEE e
JOIN EMPLOYEE other
  ON other.EMPNO <> e.EMPNO AND YEAR(CURRENT_DATE - e.BIRTHDATE) >= YEAR(CURRENT_DATE - other.BIRTHDATE)
GROUP BY EMPNO, e.BIRTHDATE

您也可以使用子查询来执行此操作,如下所示:

SELECT
    e.EMPNO
,   e.BIRTHDATE
,   YEAR(CURRENT_DATE - e.BIRTHDATE) AS AGE
,   (SELECT COUNT(*) FROM EMPLOYEE other WHERE other.EMPNO <> e.EMPNO AND YEAR(CURRENT_DATE - e.BIRTHDATE) >= YEAR(CURRENT_DATE - other.BIRTHDATE) AS COUNT
FROM EMPLOYEE e

答案 1 :(得分:0)

如果使用where .... >= ( subselect ),则子选择不得返回超过1行。我想

SELECT e.EMPNO, e.BIRTHDATE, YEAR(CURRENT_DATE - e.BIRTHDATE) AS AGE, COUNT(EMPNO) AS COUNT
FROM EMPLOYEE e
WHERE YEAR(CURRENT_DATE - e.BIRTHDATE) >=
(SELECT MAX(YEAR(CURRENT_DATE - BIRTHDATE)) FROM EMPLOYEE
WHERE EMPNO > e.EMPNO)
GROUP BY EMPNO, e.BIRTHDATE

会工作 - 注意我插入的MAX。

第二次尝试:

SELECT e.EMPNO, e.BIRTHDATE, YEAR(CURRENT_DATE - e.BIRTHDATE) AS AGE, COUNT(f.EMPNO)
from EMPLOYEE e, EMPLOYEE f
WHERE f.BIRTHDATE <= E.BIRTHDATE
and f.EMPNO <> e.EMPNO
GROUP BY e.EMPNO, e.BIRTHDATE, YEAR(CURRENT_DATE - e.BIRTHDATE)

你就是这样加入桌子的。