MySQL根据2个条件计算列

时间:2018-12-02 23:44:53

标签: mysql

我正在尝试从日志表中计算出基本的“出勤”报告。我的logs表如下所示:

TABLE logs
id  | date       | log  |
------------------------|
123 | 2018-01-01 | 1234 |
123 | 2018-01-02 |      | // Missed log
123 | 2018-01-03 | 5678 |
456 | 2018-01-01 | 5678 |
456 | 2018-01-02 | 1234 |
456 | 2018-01-03 | 1234 |

因此,空条目将导致错过日期。

所需的SELECT结果将是这样:

id  | perc  |
------------|
123 | 0.666 |
456 | 1     |

我已经尝试了以下方法,但是我不确定从这里去哪里

SELECT id, count(*) AS attended WHERE log IS NOT NULL GROUP BY id ORDER BY attended

屈服:

id  | attended |
---------------|
123 | 2        |
456 | 3        |

这使我成为其中的一部分,但是我不确定如何向其中添加missed列,然后计算百分比。稍后,我将结果添加到“用户”表中,以便将名称与日志id关联。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

在另一个答案中建议的

CASE条件在这里仅作为COUNT always counting NOT NULL records是多余的。结果,您可以简化查询:

SELECT
      id 
    , COUNT(log) AS attended 
    , COUNT(*) - COUNT(log) AS missed
    , IF(COUNT(*) > 0, count(log) / COUNT(*), NULL) AS percentage
FROM
    logs
GROUP BY
    id 
ORDER BY
    attended

此外,我已经按照OP确定了百分比计算。

答案 1 :(得分:1)

“条件聚合”解决了这个问题,基本上是将case expression放在count()函数中

SELECT
      id 
    , count(case when log IS NOT NULL then 1 end) AS attended 
    , count(case when log IS NULL then 1 end)     AS Missed
    , case when count(case when log IS NOT NULL then 1 end) > 0 then
           count(case when log IS NOT NULL then 1 end) / count(*)
           else 0
      end AS perc  
GROUP BY id 
ORDER BY attended

如果您使用count(*),则所有行都将被计数,但是如果您计算的值可以为NULL,则不会计算这些NULL。