在两个表连接

时间:2015-06-01 16:31:04

标签: sql sql-server join inner-join

我有一个标准,我希望将表1加入表2,表1包含销售人员销售的产品,表2包含销售员已售罄的销售数据。 现在我想知道每个销售的剩余产品加入。
下面是我的数据,这是我想要做的,但它只返回推销员1数据 根据我的要求,我需要帮助才能加入这些表格

CREATE TABLE Salesman_Product
(

SalesManID int,
ProductID int

)

INSERT INTO Salesman_Product (SalesManID,ProductID) Values (1,1),(1,2),(1,3),(1,4)  
INSERT INTO Salesman_Product (SalesManID,ProductID) Values (2,1),(2,2),(2,3),(2,4) 

--select * from Salesman_Product

CREATE TABLE Salesman_Sales
(

SalesManID int,
ProductID int,
Status varchar(3)

)


INSERT INTO Salesman_Sales (SalesManID,ProductID,Status) Values (1,1,'Yes'),(1,3,'Yes') 
INSERT INTO Salesman_Sales (SalesManID,ProductID,Status) Values (2,1,'Yes'),(2,2,'Yes'),(2,3,'Yes')

--select * from Salesman_Sales 

;WITH CTE_RES AS
(
SELECT * FROM Salesman_Product
WHERE ProductID NOT IN
(
SELECT Salesman_Sales.ProductID FROM Salesman_Sales INNER JOIN
Salesman_Product ON
Salesman_Sales.SalesManID =Salesman_Product.SalesManID
AND Salesman_Sales.ProductID =Salesman_Product.ProductID
--AND Salesman_Sales.SalesManID =1
)
)
SELECT * INTO #TEMP_RES FROM CTE_RES
SELECT * FROM #TEMP_RES
--DROP TABLE #TEMP_RES

必填结果

SALESMANID   PRODUCTID
1            2
1            4
2            4

1 个答案:

答案 0 :(得分:1)

使用module.controller(...

进行简单选择会让您感到困惑
module.directive(....

结果:

not exists

see fiddle here