Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case statement and group by not grouped correctly (postgresql)

How do I get correct grouping when a column not should be grouped. The query gets a wrong result

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')
;

Using a case when gives wrong result when grouped.

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 appears twice because invoices are in two types.

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

The question is simple: How can I group only by company?

I know that similar questions have been asked before, but I could not find any with case involved.

Expected output (type is not needed):

Volvo       300  4000
Apple       100  1000
Microsoft   100  4000
BMW         200  5000

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

TIA

like image 234
sibert Avatar asked May 26 '26 22:05

sibert


1 Answers

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
like image 102
Clodoaldo Neto Avatar answered May 28 '26 15:05

Clodoaldo Neto