我有这样一个测试表:Table Rows setup
我的目标是尝试获取在当前部门之前建立的部门数。我的SQL是:
SELECT A.Department, IFNULL(COUNT(*), 0)
FROM Departments A
INNER JOIN Departments B ON B.YearOfEstablishment < A.YearOfEstablishment
GROUP BY Department
ORDER BY COUNT(*);
但是我同时尝试了 LEFT JOIN
和 INNER JOIN
,最后找到的第一个部门永远不会返回,因为我可以假设一片空白。尽管有IFNULL
,但部门未显示。
我在这里做什么错了?
答案 0 :(得分:2)
我认为这是您需要的查询:
SELECT A.Department, COUNT(B.Department)
FROM Departments A
LEFT JOIN Departments B ON B.YearOfEstablishment < A.YearOfEstablishment
GROUP BY A.Department
ORDER BY 2;
请参见 this db fiddle demo 。
| Department | cnt |
| ----------------- | --- |
| Office Management | 0 |
| Business | 1 |
| Sales Management | 2 |
| ComputerScience | 3 |
| Liberal Arts | 4 |
| Farming | 4 |
| Communications | 6 |
| Digital Science | 7 |
NB:@fifonik指出,IFNULL
不需要,因为COUNT
在没有可用记录时已经返回了0
。
答案 1 :(得分:1)
在MySQL 8+中,您可以使用rank()
或row_number()
更好地做到这一点:
SELECT d.Department,
ROW_NUMBER() OVER (ORDER BY YearOfEstablishment) - 1 as seqnum
FROM Departments d
ORDER BY seqnum;
没有关系,这与您的查询相同。这样做可能更好:
SELECT d.Department,
RANK() OVER (ORDER BY YearOfEstablishment) - 1 as seqnum
FROM Departments d
ORDER BY seqnum;
这应该是您要查找的数量。
答案 2 :(得分:-1)
您还可以执行以下操作:
SELECT
A.Department
, A.YearOfEstablishment
, COUNT(*) - 1
FROM
Departments A
INNER JOIN Departments B ON (
A.id = B.id
OR B.YearOfEstablishment < A.YearOfEstablishment
)
GROUP BY
Department
ORDER BY
COUNT(*);