0

I have 3 tables:

CREATE table materials
 (id serial primary key not null,
 name varchar(50) not null,
 unit varchar(10) not null default 'шт',
 price decimal(12, 2) not null check (price>0));

CREATE table warehouses 
(id serial primary key not null,
 lastname varchar(25) not null);

CREATE table materials_in_warehouses
 (id_warehouses integer references warehouses(id) on update cascade on delete cascade,
 id_materials integer references materials(id),
 unit varchar(15) default 'шт',
 count integer not null CHECK (count>0),
 lastdate date not null, 
primary key (id_warehouses, id_materials);

And i need to select for each material : name; count of warehouses, where the material is present in an amount of > 100.

I tried to do something like this:

select materials.name, count(select * from materials_in_warehouses where 
materials.id = materials_in_warehouses.id_materials AND material_in_warehouses.count > 100) as sount from  materials;

But of course, this nonsense can't work.

Thank you in advance.

3
  • Your code has error or ... Commented Dec 21, 2015 at 18:18
  • type materials.id is serial and materials_in_warehouses.id_materials is integer !? Commented Dec 21, 2015 at 18:22
  • @ashkufaraz serial is like auto_increment in mysql. It's an integer, but with autoincrement. It's still integer. Commented Dec 21, 2015 at 18:38

3 Answers 3

1

Pretty straight forward.

SELECT m.name, count(miw.id_warehouses)
FROM materials m
LEFT JOIN materials_in_warehouses miw ON m.id=miw.id_materials AND miw."count">100
GROUP BY m.id, m.name

Your mistake might have just been the fact that you're using count as a column name, when it's an aggregate function. Use double quotes in PostgreSql for that: Escaping keyword-like column names in Postgres

Sign up to request clarification or add additional context in comments.

2 Comments

works good, but why does not output materials, where count of warehouses = 0?
Are you testing the updated version? After I had answered yesterday, I realized that it would behave like that, so I eliminated the WHERE clause, and moved the condition into the LEFT JOIN.
0

Try like this

select materials.name, count(
select id_warehouses from materials_in_warehouses join materials 
on  materials.id = materials_in_warehouses.id_materials
where material_in_warehouses.count > 100
) as sount from  materials;

Comments

0
SELECT m.name, COUNT(w.id) AS locs
  FROM materials m, warehouses w, materials_in_warehouses mw
  WHERE m.id = mw.id_materials
    AND w.id = mw.id_warehouses
    AND mw.count > 100
  GROUP BY m.name;

If that works I'll come back and explain how I came up with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.