case语句和组未正确分组(postgresql)

时间:2015-12-30 16:21:28

标签: postgresql postgresql-9.1

如果不对列进行分组,如何获得正确的分组。查询得到错误的结果

io.to(socketid).emit("message_to_client",{message : data.message});

使用案例时,在分组时给出错误的结果。

CREATE TABLE inv
    (invid int, co int4, type varchar(1), sum int4);
INSERT INTO inv
    (invid, co, type, sum)
VALUES
    (1, 1,'J',1000),
    (2, 1,'O',2000),
    (3, 2,'O',3000),
    (4, 3,'J',4000),
    (5, 4,'J',1000),
    (6, 2,'O',2000),
    (7, 1,'J',1000)
;

CREATE TABLE co
    (coid int, name varchar(30));
INSERT INTO co
    (coid, name)
VALUES
    (1,'Volvo'),
    (2,'BMW'),
    (3,'Microsoft'),
    (4,'Apple')
;

沃尔沃出现两次,因为发票有两种类型。

SELECT name,type,
CASE 
   WHEN type ='J' THEN 100
   WHEN type ='O' THEN 200
   ELSE 0 END AS cost,
sum(sum)
FROM inv
LEFT JOIN co ON coid=co
GROUP BY name,type

问题很简单:我如何只按公司分组?

我知道之前已经提出了类似的问题,但我找不到涉及案件的任何问题。

预期输出(不需要类型):

Volvo     J  100  2000
Apple     J  100  1000
Microsoft J  100  4000
BMW       O  200  5000
Volvo     O  200  2000

http://sqlfiddle.com/#!15/35c5df/5

TIA

1 个答案:

答案 0 :(得分:3)

select
    name,
    sum ( case
       when type = 'J' then 100
       when type = 'O' then 200
       else 0 end
    ) as cost,
    sum("sum") as "sum"
from inv left join co on coid=co
group by name