mysql设置为0

rks48beu  于 2021-07-29  发布在  Java
关注(0)|答案(4)|浏览(202)

我想统计每个地区所有员工的情况,这些情况有两个参数,好的和不好的。这样地,

conditions    |    area    |    count_conditions
   Well           AREA1               1
  UNWELL          AREA1               0
   Well           AREA2               5
  UNWELL          AREA2               1
...

这是迄今为止最接近的一次。

SELECT a.conditions, k.area, 
        SUM(CASE WHEN a.conditions IS NOT NULL THEN 1 ELSE 0 END) AS count_conditions
FROM tb_attended a
INNER JOIN tb_employees k ON a.nrp = k.nrp
    AND a.date = '2020-07-20'
GROUP BY k.area, a.conditions

我上面的代码运行良好,但如果在某些区域没有不适或井的进入,则不会出现这种情况。这样地。

conditions    |    area    |    count_conditions
   Well           AREA1               1
   Well           AREA2               5
  UNWELL          AREA2               1
...

这是我使用的示例数据,sql fiddle
有什么建议吗?谢谢您。

lrpiutwd

lrpiutwd1#

首先需要不同区域与不同条件的交叉联接,然后是表的左联接:

SELECT t1.condition, t2.area, 
       COUNT(k.nrp) AS count_conditions
FROM (SELECT DISTINCT `condition` FROM tb_attended) t1
CROSS JOIN (SELECT DISTINCT Area FROM tb_employees) t2
LEFT JOIN tb_attended a ON a.condition = t1.condition
LEFT JOIN tb_employees k ON k.area = t2.area AND a.nrp = k.nrp AND a.date = '2020-07-20'
GROUP BY t1.condition, t2.area
ORDER BY t2.area, t1.condition DESC

请看演示。

mf98qq94

mf98qq942#

使用左连接

SELECT a.conditions, k.area, 
        SUM(CASE WHEN a.conditions IS NOT NULL THEN 1 ELSE 0 END) AS count_conditions
FROM tb_attended a
left JOIN tb_employees k
ON a.nrp = k.nrp
AND a.date = '2020-07-20'
GROUP BY k.area, a.conditions
nfeuvbwi

nfeuvbwi3#

你可以用 LEFT JOIN 没有多余的条件语句,有 SUM() 聚合:

SELECT a.conditions, k.area, 
       SUM(a.conditions IS NOT NULL) AS count_conditions
  FROM tb_attended a
  LEFT JOIN tb_employees k
    ON a.nrp = k.nrp
   AND a.date = '2020-07-20'
 GROUP BY k.area, a.conditions
wnavrhmk

wnavrhmk4#

我想你想要一个 left join :

SELECT a.conditions, k.area, COUNT(a.conditions) AS count_conditions
FROM tb_employees k LEFT JOIN
     tb_attended a
     ON a.nrp = k.nrp AND a.date = '2020-07-20'
GROUP BY k.area, a.conditions;

编辑:
我懂了。你想得到所有的行,甚至那些没有匹配的。使用 CROSS JOIN 生成所需区域和条件的组合。然后使用 LEFT JOIN 要匹配现有数据:

SELECT c.condition, e.area, COUNT(a.nrp) AS count_conditions
FROM (SELECT DISTINCT a.condition 
      FROM tb_attended a
     ) c CROSS JOIN
     (SELECT DISTINCT area
      FROM tb_employees
     ) e LEFT JOIN
     tb_employees k
     ON k.area = e.area LEFT JOIN
     tb_attended a
     ON a.nrp = k.nrp AND 
        a.condition = c.condition AND
        a.date = '2020-07-20'
GROUP BY c.condition, e.area;

这是一把小提琴。

相关问题