![](/img/trans.png)
[英]How to return rows from left table where condition on right table true on all row without sub query
[英]How to get all row from left table multiply for right table
我有以下兩個表:
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
我想要一個帶有所有產品列表*代理商列表的表格。 因此,對於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, -
使用:
SELECT *
FROM ProductTable
LEFT JOIN AgentTable
ON ProductTable.Product = SalesTable.Product
顯然不行。
你可以這樣嘗試
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)
試試這個查詢
SELECT ST.*
FROM ProductList PL
JOIN SalesTable ST ON PL.Product = ST.Product
ORDER BY ST.Agent, ST.Product
根據需要刪除了分組依據,但未分組
SQLFiddle- http: //www.sqlfiddle.com/#!2/30335/18
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.