I've the following two tables:
Table: ProductList
Product;
Product a
Procuct b
Product c
...
Product Z
Table: SalesTable
Agent, Product, Qty
ZXY, Product A, 200
ABC, Product A, 100
ABC, Product B, 200
I would like to have a table with ALL product List * Agent list. So, for instnace :
Agent, Product, Qty
ZXY, Product A, 200
ZXY, Product B, -
ZXY, Product C, -
....
ABC, Product A, 100
ABC, Product B, 200
ABC, Product C, -
ABC, Product D, -
Using :
SELECT *
FROM ProductTable
LEFT JOIN AgentTable
ON ProductTable.Product = SalesTable.Product
not work, obviously.
You can try like this
Select Distinct B.Agent,A.Product,C.Qty
from
Product A
Cross JOIN SalesTable B
Left join SalesTable C on C.Product=A.Product and C.Agent=B.AGENT
SELECT t1.Agent, t1.Product, COALESCE(s.Qty, '-') AS Qty
FROM (
SELECT a.Agent, p.Product
FROM (SELECT DISTINCT Agent FROM SalesTable) a
CROSS JOIN
(SELECT DISTINCT Product FROM ProductList) p
) t1 LEFT JOIN SalesTable s
ON (t1.Product = s.Product
AND t1.Agent = s.Agent)
Try this query
SELECT ST.*
FROM ProductList PL
JOIN SalesTable ST ON PL.Product = ST.Product
ORDER BY ST.Agent, ST.Product
Removed Group By, as order was required and not grouping
SQLFiddle - http://www.sqlfiddle.com/#!2/30335/18
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.