MS SQL Server 2008查询中的独特记录问题

时间:2009-08-27 01:11:17

标签: sql sql-server-2008

我有这个查询来获取值为1和5的OrderStatus总数。如何仅对Sum.OrderStatus = 2进行求和,因为OrderSttails表中有多个记录,OrderStatus为2。

请帮忙

SELECT O.OrderDate,
Sum(Case When OD.OrderStatus = 2 Then 1 Else 0 End) AS OrdersOffered,
Sum(Case When OD.OrderStatus = 1 Then 1 Else 0 End) AS OrdersAccepted
FROM Orders O,OrderDetails OD
Where O.Order_ID=OD.Order_ID
GROUP BY OrderDate

2 个答案:

答案 0 :(得分:1)

所以,你想要它是1,不管你有多少?也许使用SIGN?

SELECT O.OrderDate
  ,SIGN(Sum(Case When OD.OrderStatus = 2 Then 1 Else 0 End)) AS OrdersOffered
  ,Sum(Case When OD.OrderStatus = 1 Then 1 Else 0 End) AS OrdersAccepted
FROM Orders O
  JOIN OrderDetails OD  ON O.Order_ID=OD.Order_ID
GROUP BY OrderDate

答案 1 :(得分:0)

只需使用子查询来帮助您获得结果。

SELECT 
O.OrderDate, 
Sum(Case When OD.OrderStatus = 2 Then 1 Else 0 End) AS OrdersOffered, 
Sum(Case When OD.OrderStatus = 1 Then 1 Else 0 End) AS OrdersAccepted 
FROM Orders O inner join
    (Select distinct Order_ID,OrderStatus 
    from OrderDetails) OD on O.Order_ID=OD.Order_ID
GROUP BY OrderDate 

应该做的诀窍......