SQL不是我的强项,我正在努力寻找这个问题的解决方案。我试图弄清楚如何根据以下逻辑得到结果集。当A不在B中时选择记录A或如果记录出现在B和A中则选择B.我尝试了以下联合,它返回了我在两个表中当天匹配的所有记录,但我无法弄清楚如何拉我需要从两个表中获得的数据。
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate())
答案 0 :(得分:2)
您可以执行左外连接,并在select中使用ISNULL或CASE语句来返回所需的值。
我将证明:
SELECT
CASE WHEN b.iPurchaseOrderLineId IS NOT NULL THEN 'b' ELSE 'a' END AS [Source],
a.iPurchaseOrderLineId,
ISNULL(b.sProductDescription, a.sProductDescription) AS [sProductDescription]
FROM PurchaseOrderLine AS a
LEFT JOIN GoodsIn AS b ON a.iPurchaseOrderLineId = b.iPurchaseOrderLineId
AND b.dDateDelivered = GETDATE()
WHERE b.iPurchaseOrderLineId IS NOT NULL
OR a.dRequiredDate = CONVERT(DATE, GETDATE())
希望有所帮助!
答案 1 :(得分:1)
希望这会对你有所帮助:只是一个与你相似的例子。
create table A(id int , name char(12))
go
create table B(id int , name char(12))
go
insert into A values (1,'ABC'),(3,'WXY')
insert into B values (1,'ABC'),(2,'AAA')
SELECT a.id,a.name FROM A EXCEPT SELECT * FROM B
UNION
SELECT a.id,a.name FROM A inner join b on a.id=b.id and a.name=b.name
感谢!!!
答案 2 :(得分:1)
如果我理解正确,假设GoodsIn = B,你可以尝试这种方式。
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
LEFT JOIN GoodsIn
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
AND GoodsIn.iPurchaseOrderLineId IS NULL
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate());
你也可以按照你所描述的那样逐字尝试(假设sProductDescription在PurchaseOrderLine中):
"当A不在B"
时选择记录A.SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE iPurchaseOrderLineId NOT IN(SELECT iPurchaseOrderLineId FROM GoodsIn)
或以这种方式:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE NOT EXISTS(SELECT * FROM GoodsIn
WHERE GoodsIn.iPurchaseOrderLineId=PurchaseOrderLine.iPurchaseOrderLineId)
或使用EXCEPT:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
EXCEPT
SELECT 'a', iPurchaseOrderLineId, sProductDescription
FROM GoodsIn;
只需提示,根据您的需求量身定制。