0

这是我的 SQL:

-- Order information
SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount, o.OrderDate, o.PublicNotes, u.userid, PostAmount + TaxAmt AS Total, PostAmount - PaymentAmt AS Due
FROM Orders o 
INNER JOIN Payment p ON p.OrderID = o.OrderID
INNER JOIN Users u  ON o.EnteredBy = u.UserKey
Where o.OrderID = 5267

现在对于这个特定的 OrderID,它只返回 0 行只是列标题。有没有办法强制它为值返回 0 并为其余部分返回空字符串?

4

2 回答 2

5

我认为它应该给你想要的结果:

WITH CTE1 AS (SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount,  
   o.OrderDate, o.PublicNotes, u.userid, PostAmount + TaxAmt AS Total, PostAmount -    
    PaymentAmt AS Due 
    FROM Orders o  
    INNER JOIN Payment p ON p.OrderID = o.OrderID 
    INNER JOIN Users u  ON o.EnteredBy = u.UserKey 
    Where o.OrderID = 5267 
    AND o.EnteredBy = u.UserKey )
SELECT CTE1.*
FROM CTE1
UNION ALL
SELECT 0,0, NULL,NULL,NULL,NULL,NULL
WHERE NOT EXISTS (SELECT 1 FROM CTE1)
于 2012-05-01T22:01:37.640 回答
2

其他方式:

SELECT ISNULL(p.PaymentAmt, 0) AS PaymentAmt, o.TaxAmt, o.PostAmount, 
       o.OrderDate, o.PublicNotes, u.userid, 
       PostAmount + TaxAmt AS Total, PostAmount - PaymentAmt AS Due
FROM Orders o 
  INNER JOIN Payment p ON  p.OrderID = o.OrderID
                       AND o.OrderID = 5267        --- condition moved here
  INNER JOIN Users u  ON o.EnteredBy = u.UserKey
  RIGHT JOIN (SELECT 1 dummy) trick ON 1=1         --- this line was added

---  AND o.EnteredBy = u.UserKey                   --- this is redundant
于 2012-05-01T22:14:26.560 回答