1

我有一个疑问,

SELECT E.staffid AS staff
SUM(E.Frequency='Less') AS lessCount, 
SUM(E.Frequency='More') AS moreCount,  
FROM effort_frequency E 
INNER JOIN ost_staff S ON S.staff_id = E.staffid 
WHERE E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 
GROUP BY E.staffid

我得到下表,

+-------+-----------+-----------+
| Staff | lessCount | moreCount |
+-------+-----------+-----------+
|  1    |    2      |     3     |
|  3    |    1      |     4     |
|  5    |    2      |     3     |
+-------+-----------+-----------+

您可以看到结果中缺少2 和 4,对于给定的日期,表中不会有 staff_id 2 和 4 的effort_frequency,但我正在尝试加入ost_staff表,这样我就可以获得类似下表中,ost_staff 将包含所有员工 ID,比如说 1-5。

+-------+-----------+-----------+
| Staff | lessCount | moreCount |
+-------+-----------+-----------+
|  1    |    2      |     3     |
|  2    |    0      |     0     |
|  3    |    1      |     4     |
|  4    |    0      |     0     |
|  5    |    2      |     3     |
+-------+-----------+-----------+

我尝试了外部连接,但它不起作用,我想我在某个地方犯了错误。

4

2 回答 2

2

WHERE子句移至ON子句,并将 更改INNER JOINRIGHT JOIN。并将其更改GROUP BY E.staffidGROUP BY S.staff_id; 同样将其SELECT E.staffid,更改为SELECT s.staff_id

SELECT S.staff_id AS staff

    COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
    COALESCE(SUM(E.Frequency='More'),0) AS moreCount,  

FROM effort_frequency E 

RIGHT JOIN ost_staff S 
ON S.staff_id = E.staffid 
AND E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 

GROUP BY S.staff_id

如果要使用LEFT JOIN,请切换表 ost_staff 和努力频率:

SELECT S.staff_id AS staff

    COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
    COALESCE(SUM(E.Frequency='More'),0) AS moreCount,  

FROM ost_staff S 

LEFT JOIN effort_frequency E 
ON S.staff_id = E.staffid 
AND E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 

GROUP BY s.staff_id

您也可以使用 IFNULL 代替 COALESCE。IFNULL 仅适用于 MySQL

于 2012-05-23T05:24:45.323 回答
1

您是否尝试过 LEFT JOIN

SELECT E.staffid AS staff
       COALESCE(SUM(E.Frequency='Less'),0) AS lessCount, 
       COALESCE(SUM(E.Frequency='More'),0) AS moreCount,  
FROM effort_frequency E LEFT JOIN ost_staff S 
      ON S.staff_id = E.staffid 
WHERE E.log_date BETWEEN '2012-05-01' AND '2012-05-23' 
GROUP BY E.staffid

学习 SQL JOINS 的文章

添加COALESCE是因为如果不存在记录,它将返回NULL值。

于 2012-05-23T05:16:29.267 回答