我有3个表,即客户,信用和付款。我希望得到客户在@StartDate和@EndDate之间做出的所有付款和信用。这是我的查询:
SELECT Client.Name, Payment.PaymentAmount, Credit.CreditAmount
FROM Client
LEFT JOIN Payment
ON Client.ClientID = Payment.ClientID
LEFT JOIN Credit
ON Client.ClientID = Credit.ClientID
WHERE (Payment.Date BETWEEN @StartDate AND @EndDate) AND (Client.Date BETWEEN @StartDate AND @EndDate)
ORDER BY Client.CName
我想显示所有信用额度,即使付款没有用信用卡支付,而支票也是NULL,反之亦然。但我无法得到它,因为它只显示该客户在该日期的信用和付款。
我尝试过OR而不是AND(使用' WHERE')但它也不起作用。
答案 0 :(得分:2)
您可以通过将条件移至on
子句来获得所需内容:
SELECT c.Name, p.PaymentAmount, cr.CreditAmount
FROM Client c LEFT JOIN
Payment p
ON c.ClientID = p.ClientID AND p.Date BETWEEN @StartDate AND @EndDate LEFT JOIN
Credit cr
ON c.ClientID = cr.ClientID AND cr.Date BETWEEN @StartDate AND @EndDate
ORDER BY c.CName;
但是,我不确定这是你真正想要的东西,因为它在支付和信用之间做了一个笛卡尔产品,在这段时间内不止一个。
这可能更接近你真正想要的东西:
SELECT c.Name, p.PaymentAmount, NULL as CreditAmount
FROM Client c LEFT JOIN
Payment p
ON c.client_id = p.ClientId AND p.Date BETWEEN @StartDate AND @EndDate
UNION ALL
SELECT c.Name, NULL, c.CreditAmount
FROM Client c LEFT JOIN
Credit cr
ON c.ClientID = cr.ClientID AND cr.Date BETWEEN @StartDate AND @EndDate
ORDER BY Name;