选择结果集行到列转换

时间:2012-04-18 06:41:42

标签: sql postgresql select

我有一个表格remarks,其中id, story_id, like列可以是+1-1 我希望我的select查询返回以下列story_id, total, n_like, n_dislike,其中total = n_like + n_dislike没有子查询。

我目前正在group bylike select进行like as like_t, count(like) as total,这会给我输出

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

并在结果集中返回两行。但我想要的是1行,其中n_like is 6和n_dislike是2total8

1 个答案:

答案 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"