Which make of SQL are you using? I am most familiar with Microsoft SQL Server. Syntactically, you need to move the WHERE
after all of the JOIN
statements. (I appended the tablename L to its references for consistency.)
select * from L
left outer join ER on ER.childid=L.id
left outer join E on E.id=ER.parentid
left outer join M on M.id=ER.parentid
where L.xpos > 5
This is legal syntax. The next question is what results you want. I think possibly so, although you did not show a sample of results. Perhaps you can play with the data a bit to decide what you need.
CREATE table E (id INT, title varchar(50), [datetime] DateTime);
CREATE table L (id INT, place varchar(50), xpos float, ypos float);
CREATE table M (id INT, title varchar(50), [datetime] DateTime, contact varchar(50), agenda varchar(50));
CREATE table ER (parentid INT, childid INT, parenttype INT, childtype INT);
INSERT INTO L VALUES (1, 'Boston',123.234, 23.234);
INSERT INTO L VALUES (3, 'Miami', 456.234, 78.234);
INSERT INTO ER VALUES (100,1, 5, 4);
INSERT INTO ER VALUES (200,2, 5, 4);
INSERT INTO ER VALUES (200,3, 5, 4);
INSERT INTO ER VALUES (100,4, 5, 4);
INSERT INTO E VALUES (100, 'Able','2014/01/02');
INSERT INTO E VALUES (2, 'Baker','2014/01/11');
INSERT INTO M VALUES (100, 'Love', '2014/04/04', 'George', 'None');
INSERT INTO M VALUES (200, 'Fury', '2014/05/05', 'Bernard', 'Something big');
SELECT * FROM L
LEFT OUTER JOIN ER on ER.childid = L.id
LEFT OUTER JOIN E on E.id= ER.parentid
LEFT OUTER JOIN M on M.id= ER.parentid
WHERE L.xpos > 5
DROP TABLE E
DROP TABLE L
DROP TABLE M
DROP TABLE ER
The query is joining 2 tables (receipts, sales) that both have a many-to-one relationship with product
. This creates a kind of cartesian (cross) product and will give wrong results in the SUM()
calculations. To avoid that, you need to do the summations for the two tables in two different subqueries to avoid errors.
Something like this will work:
SELECT
m.month,
p.name,
COALESCE(r.receipts_quantity, 0) AS receipts_quantity,
COALESCE(s.sales_quantity, 0) AS sales_quantity
FROM
product AS p
CROSS JOIN
( VALUES (1),(2),(3),(4),(5),(6) ) AS m(month) -- months wanted in the report
LEFT OUTER JOIN
( SELECT month, product_id, SUM(quantity) AS receipts_quantity
FROM receipts
GROUP BY month, product_id
) AS r
ON p.id_product = r.product_id
AND m.month = r.month
LEFT OUTER JOIN
( SELECT month, product_id, SUM(quantity) AS sales_quantity
FROM sales
GROUP BY month, product_id
) AS s
ON p.id_product = s.product_id
AND m.month = s.month ;
If you want to avoid having results for products that did not have any activity in a month, you can add the condition:
WHERE r.month IS NOT NULL
OR s.month IS NOT NULL
Best Answer
You can use Coalesce to show s.amount or p.amount which one is not null:
Query:
create schema:
Check the db-fiddle link: https://www.db-fiddle.com/#&togetherjs=E7luJAKsF5