我有以下型号。 Posts
和Reactions
。
现在我想得到所有帖子的清单,以及某人对该帖子做出反应的频率和方式,即
id | reaction | count
---+----------+------
1 | like | 13
1 | dislike | 1
3 | like | 89
到目前为止,我的目标是:
SELECT posts.id, reactions.reaction, COUNT(reactions.reaction)
FROM posts JOIN reactions on posts.id = reactions.post_id
GROUP BY posts.id, reactions.reaction
但这似乎只计算并显示总反应,我需要添加什么才能得到每种反应类型的结果?
如果它只能将反应计数显示为列,那就更好了。即。
id | lik | dislike
---+-----+------
1 | 13 | 1
3 | 89 | 0
我仍然在玩crosstab
以获得这个要点。
答案 0 :(得分:0)
只需使用case
表达式
SELECT
p.id,
SUM(CASE WHEN r.reaction = 'like' THEN 1 ELSE 0 END) like,
SUM(CASE WHEN r.reaction = 'dislike' THEN 1 ELSE 0 END) dislike
FROM posts p
INNER JOIN reactions r on p.id = r.post_id
GROUP BY p.id
答案 1 :(得分:0)
希望它可以帮到你:
SELECT id,
SUM(CASE WHEN reaction = 'like' THEN Lik ELSE 0 END) [like],
SUM(CASE WHEN reaction = 'dislike' THEN Dislike ELSE 0 END) dislike
FROM Reactions
GROUP BY id