在一张桌子中算出三个可能性

时间:2019-01-09 08:12:48

标签: mysql sql

我有一个带有订阅者的表,该订阅者有两个字段,分别是active和suscribed。我需要获取同一咨询中订户的总数,已激活的数量和已订阅的数量。我试图用双左联接来做到这一点,但我需要按不是主键的字段分组,但会出错。我现在有这样的咨询:

FROM (SELECT subscribers.mailing_list, subscribers.mailing_list AS suscriptores, s2.inactivos AS inactivos, s3.excluidos AS excluidos
FROM subscribers
LEFT JOIN (SELECT id, mailing_list, COUNT(*) AS inactivos FROM subscribers WHERE subscribed = false GROUP BY id) s2 ON subscribers.id = s2.id
LEFT JOIN (SELECT id, mailing_list, COUNT(*) AS excluidos FROM subscribers WHERE excluded = true GROUP BY id) s3 ON subscribers.id = s3.id
) AS subs
GROUP BY subs.mailing_list```

2 个答案:

答案 0 :(得分:0)

您不需要{3}查询,而是需要在聚合函数中使用case expressions,这称为“条件聚合”,例如

SELECT
        mailing_list
      , COUNT( CASE WHEN subscribed = FALSE THEN 1 END ) AS inactivos
      , COUNT( CASE WHEN subscribed = TRUE  THEN 1 END ) AS excluidos
      , COUNT( * ) AS Total
FROM subscribers
GROUP BY
        mailing_list

答案 1 :(得分:0)

在MySQL中,您可以将此逻辑简化为:

SELECT mailing_list,
       SUM( subscribed = FALSE ) AS inactivos,
       SUM( subscribed = TRUE ) AS excluidos,
       COUNT( * ) AS Total
FROM subscribers
GROUP BY mailing_list;

如果subscribed实际上是boolean,则可以将其进一步简化为:

SELECT mailing_list,
       SUM( NOT subscribed ) AS inactivos,
       SUM( subscribed ) AS excluidos,
       COUNT( * ) AS Total
FROM subscribers
GROUP BY mailing_list;