如何将三个计数查询合并为一个

时间:2018-03-08 01:47:48

标签: sql database count

如何使用不同的反应(viewedSELECT COUNT(DISTINCT user_id) FROM reactions WHERE post_id = $1 AND reaction 'like'; )将此类查询与其他两个查询相结合,以便我可以通过一个查询收集统计信息?

function bulk_set_observable(obj, replacements) {
    for (let key in replacements) {
        obj[key] = replacements[key];
    }
}

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT
    user_id,
    COUNT(DISTINCT CASE WHEN reaction = 'like'    THEN 1 END) AS like_cnt,
    COUNT(DISTINCT CASE WHEN reaction = 'dislike' THEN 1 END) AS dislike_cnt,
    COUNT(DISTINCT CASE WHEN reaction = 'viewed'  THEN 1 END) AS viewed_cnt
FROM reactions
WHERE post_id = $1
GROUP BY user_id;

从您的问题中,您是否希望将这些统计信息用于单个用户或整个表格,这一点并不完全清楚。如果是后者,那么我们可以按user_id进行汇总,并为每个用户生成这些统计信息。

答案 1 :(得分:1)

我想像这样:

SELECT reaction,count(DISTINCT user_id) FROM reactions
WHERE post_id=$1 AND reaction in ('like','dislike','viewed')
GROUP BY reaction