我需要幫助。我有這樣的SQL語句:使用Sql Server中的單個搜索條件搜索多個表格
ALTER proc [dbo].[GetDSR]
(
@WholeSellerId varchar(50),
@FromDate date
)
as
begin
with cte1 as
(select co.ProductId as copid, co.DateAdded as coda, sum(isnull(co.quantity,0)) as coq, co.WholeSellerId as coid
from ConsignmentSale co
group by co.ProductId, co.DateAdded, co.WholeSellerId),
cte2 as
(select ca.ProductId as caid, sum(isnull(ca.quantity,0)) as caq from CashSale ca
group by ca.ProductId),
cte3 as
(select wi.ProductId as wiid, sum(isnull(wi.Quantity,0)) as wiq from Withdrawal wi
group by wi.ProductId),
cte4 as
(select po.ProductId as poid, sum(isnull(po.Quantity,0)) as poq from Pullout po
group by po.ProductId),
cte5 as
(select pr.ProductId as prid, sum(isnull(pr.Quantity,0)) as prq from Promotion pr
group by pr.ProductId)
select cte1.copid as Product, cte1.coda, isnull(cte1.coq,0) as Credit, isnull(cte2.caq,0) as Cash,
isnull(cte3.wiq,0) as Withdrawal, isnull(cte4.poq,0) as Pullout, isnull(cte5.prq,0) as Promotion
from cte1
full outer join cte2 on cte2.caid=cte1.copid
full outer join cte3 on cte3.wiid=cte1.copid
full outer join cte4 on cte4.poid=cte1.copid
full outer join cte5 on cte5.prid=cte1.copid
where cte1.coid = @WholeSellerId and cte1.coda = @FromDate
end
go
它給了我正確的結果只有當在ConsignmentSale滿足特定條件的數據。問題是,如果ConsignmentSale中沒有滿足條件的數據,但在其他表中存在數據,則不會顯示該數據。大概是因爲這部分的:
where cte1.coid = @WholeSellerId and cte1.coda = @FromDate
它僅使用標準單一表中,ConsignmentSale,它不檢查表的其餘部分符合這個標準。請告訴我如何改變這個過程,即使在ConsignmentSale中不符合條件,但在另一個表中符合條件,它仍然會給我結果,並且coq只會爲0,因爲它會沒有符合該標準的數據。 謝謝。
它仍然沒有給我正確的結果。我認爲問題在於我的搜索條件。在最後一條SELECT語句中,我只獲取cte1.copid,這意味着它只會顯示來自ConsignmentSale的ProductId。但是如果ConsignmentSale中的條件不符合我的標準,那麼這意味着它不會再打印ProductId。 – Ibanez1408
cte1和cte2之間的第一個FULL JOIN具有在cte1和cte2之間匹配的行以及cte1或cte2中不匹配的行。對於cte2中與cte1(FULL JOIN的RIGHT JOIN部分)不匹配的行,cte1.copid將爲NULL。然後看看第二個FULL JOIN規範:'ON cte3.wiid = cte1.copid'。對於cte2中不匹配cte1的行,cte1.copid爲NULL,因此此條件不會滿足第一個FULL JOIN的RIGHT JOIN部分。也許這是有意的,但我懷疑它。 –
並重讀他的查詢,他在WHERE子句中有這個:'cte1.coid = @ WholeSellerId'。含義cte1.coid不能爲NULL,因此他用FULL JOIN構建的整個構造都是假的。查詢將輸出,就像查詢是用LEFT JOIN寫的一樣(但可能比他以這種方式編寫查詢的性能更低)。 –