Q:

How to compose select request using many-to-many relationship in PostgreSQL?

I have this tables:
  
CREATE TABLE orders (
  order_id serial PRIMARY KEY
, number_of_things int
);

CREATE TABLE things (
  thing_id  serial PRIMARY KEY
, cost int
);

CREATE TABLE orders_to_things (
  order_id int REFERENCES orders (order_id)
, thing_id int REFERENCES things (thing_id)
);

How to compose a request for select all orders where cost of things more than some number?
I tried to use:   
SELECT orders.order_id 
FROM orders 
  INNER JOIN orders_to_things ON (orders_to_things.order_id = orders.order_id)  
  JOIN things ON (orders_to_things.thing_id=things.thing_id) 
WHERE (select SUM(things.cost) FROM things) > *some number*

but didn't get the correct result.

A:

Try this:
SELECT O.order_id, sum(T.cost)
FROM orders O
INNER JOIN orders_to_things ON orders_to_things.order_id = orders.order_id  
JOIN things T ON orders_to_things.thing_id=things.thing_id 
GROUP BY O.order_id
HAVING T.cost > 'number....'

