0

我有一个带有can be 之类remarks的列的表, 我希望我的查询返回没有子查询的以下列。id, story_id, like+1-1
selectstory_id, total, n_like, n_disliketotal = n_like + n_dislike

我目前正在做一个group byon likeand selecting like as like_t, count(like) as total,这给了我一个输出,比如

-- like_t --+ --- total --
    -1      |      2
     1      |      6

并在结果集中返回两行。但我想要的是得到1行 where n_like is 6and n_dislike is 2and totalis8

4

1 回答 1

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"专栏中的情况。

于 2012-04-18T06:58:05.033 回答