我有一个表格remarks
,其中id, story_id, like
列可以是+1
,-1
我希望我的select
查询返回以下列story_id, total, n_like, n_dislike
,其中total = n_like + n_dislike
没有子查询。
我目前正在group by
和like
select
进行like as like_t, count(like) as total
,这会给我输出
-- like_t --+ --- total --
-1 | 2
1 | 6
并在结果集中返回两行。但我想要的是1
行,其中n_like is 6
和n_dislike是2
而total
是8
答案 0 :(得分:1)
首先,LIKE
是PostgreSQL中的保留字,所以你必须加倍引用它。也许应该为这个专栏选择一个更好的名字。
CREATE TABLE testbed (id int4, story_id int4, "like" int2);
INSERT INTO testbed VALUES
(1,1,'+1'),(1,1,'+1'),(1,1,'+1'),
(1,1,'+1'),(1,1,'+1'),(1,1,'+1'),
(1,1,'-1'),(1,1,'-1');
SELECT
story_id,
sum(CASE WHEN "like" > 0 THEN abs("like") ELSE 0 END) AS n_like,
sum(CASE WHEN "like" < 0 THEN abs("like") ELSE 0 END) AS n_dislike,
count(story_id) AS total
-- for cases +2 / -3 in the "like" field, use following construct instead
-- sum(abs("like")) AS total
FROM testbed
GROUP BY story_id;
我在abs("like")
列中有+2
或-3
的情况下使用"like"
。