初学SQL语句

时间:2012-05-04 07:03:41

标签: mysql sql

我正在制作佣金报告,如果订单中包含自定义运费,则需要包含这些报告。下面我加入了两张桌子。如果OrderDetails.Custom包含'Freight''Overnight',我需要它来显示'OrderDetails.CustomPrice'

如果OrderDetails.Custom不包含'Freight''Overnight'我需要将OrderDetails.CustomPrice留空,但只要WHERE显示所有其他字段条款得到满足。

非常感谢任何帮助!


SELECT Orders.OrderDate, Orders.OrderID,      Orders.PaymentAmount, 
       Orders.Shipping,  OrderDetails.Custom, OrderDetails.CustomPrice  
FROM Orders
  JOIN OrderDetails 
    ON OrderDetails.OrderID = Orders.OrderID
WHERE OrderDate BETWEEN '04/01/12 00:00:01' 
                    AND '04/30/12 11:59:59' 
  AND SalesRep_CustomerID = '21140';

2 个答案:

答案 0 :(得分:2)

您可以通过案例陈述实现您想要的目标:

SELECT Orders.OrderDate, Orders.OrderID, Orders.PaymentAmount, Orders.Shipping, 
CASE WHEN (OrderDetails.Custom = 'Freight' OR OrderDetails.Custom = 'Overnight') THEN OrderDetails.CustomPrice ELSE '' END AS  CustomPrice,
 OrderDetails.CustomPrice  
FROM Orders
JOIN OrderDetails ON OrderDetails.OrderID = Orders.OrderID
WHERE OrderDate BETWEEN '04/01/12 00:00:01' AND '04/30/12 11:59:59' and SalesRep_CustomerID = '21140';

答案 1 :(得分:0)

使用case语句获取“CustomPrice”列

的值