具有MAX条件的Postgresql GROUP BY

时间:2015-03-05 17:58:21

标签: sql postgresql

此查询计算按渠道(地区)分组的加权平均值。我想添加一个额外的过滤器,只考虑最新的period进行计算。问题是最新的period未知(它不是日期列,而是整数,并且不是我的选择)。所以我必须先解决它才能使用它。

我尝试在AND MAX(period)子句中使用WHERE,但Postgresql不会让我在where子句中使用聚合函数。

SELECT
    channel, weight, label,
    (promoter  * 100) / weight AS promoter_p,
    (passive   * 100) / weight AS passive_p,
    (detractor * 100) / weight AS detractor_p,
    (promoter - detractor) * 100 / weight AS nps
FROM
    (
        SELECT
            channel,
            regions.name AS label,
            COUNT(surveys.id) AS base,
            SUM(weight),
            SUM(CASE WHEN var BETWEEN 9 AND 10 THEN weight END) AS promoter,
            SUM(CASE WHEN var BETWEEN 7 AND 8  THEN weight END) AS passive,
            SUM(CASE WHEN var BETWEEN 0 AND 6  THEN weight END) AS detractor
        FROM surveys
        INNER JOIN regions ON regions.code = surveys.channel
        WHERE (var BETWEEN 0 AND 10) AND active = 1
        GROUP BY channel, label
        ORDER BY label ASC
    ) t

2 个答案:

答案 0 :(得分:2)

尝试添加此条件:

...
WHERE (var BETWEEN 0 AND 10) AND active = 1
AND period = (SELECT MAX(period) FROM surveys)

答案 1 :(得分:1)

SELECT
    channel, weight, label,
    (promoter  * 100) / weight AS promoter_p,
    (passive   * 100) / weight AS passive_p,
    (detractor * 100) / weight AS detractor_p,
    (promoter - detractor) * 100 / weight AS nps
FROM
    (
        SELECT
            channel,
            regions.name AS label,
            COUNT(surveys.id) AS base,
            SUM(weight) as weight,
            SUM(CASE WHEN var BETWEEN 9 AND 10 THEN weight END) AS promoter,
            SUM(CASE WHEN var BETWEEN 7 AND 8  THEN weight END) AS passive,
            SUM(CASE WHEN var BETWEEN 0 AND 6  THEN weight END) AS detractor
        FROM surveys
        INNER JOIN regions ON regions.code = surveys.channel
        INNER JOIN (SELECT MAX(period) as max from surveys) x ON period = max
        WHERE (var BETWEEN 0 AND 10) AND active = 1
        GROUP BY channel, label
        ORDER BY label ASC
    ) t