I prepared sql fiddle: http://sqlfiddle.com/#!15/62e65/2
And schema is here:
CREATE TABLE products
("id" int, "name" varchar(5))
;
INSERT INTO products
("id", "name")
VALUES
(1, 'Car'),
(2, 'Phone')
;
CREATE TABLE operations
("id" int, "product_id" int, "status" varchar(7), "type" varchar(8))
;
INSERT INTO operations
("id", "product_id", "status", "type")
VALUES
(1, 1, 'pending', 'invoice'),
(2, 1, 'done', 'delivery'),
(3, 2, 'done', 'delivery'),
(3, 2, 'done', 'invoice')
;
I know that the data schema could be better, but I don't have possibility to refactor it now - I am just adding new view. Note about schema: product has always 2 operations: invoicing and delivery. What I want to achieve is to get such result:
name status
car pending
phone done
Where product status is a string returned after checking both product operations.
Rule is that product status is done only when both operations are done, otherwise its pending.
How to write such query in postgres?