views:

179

answers:

2

Hello, I have this query to fetch the total OrderStatus that have values 1 and 5. How do I Sum only distinct OD.OrderStatus=2 as there can be multiple records in Orderdetails table with OrderStatus as 2.

Please help

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
+1  A: 

So, you want it to be 1, regardless of how many you have? Maybe use 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
Rob Farley
Thanks. I think I need SUM(Sign(Case When OD.OrderStatus = 2 Then 1 Else 0 End)) AS OrdersOfferedI need to try it tomorrow. I don't know if it will work
acadia
No. Suppose you have ten OrderStatus = 2 records. SUM(SIGN( will add many 1s to get 10. You want to convert the 10 (Sum) back to a 1. So it's SIGN(SUM(, not SUM(SIGN(.
Rob Farley
Thanks Rob. Here is my concern. The above query I have a date range in where clause. It returns for each date in the range it will display orderdate,ordersoffered,ordersaccepted.But OrderID 10010 may have 10 orders with status as 2 but it should consider only 1 but for the same date The sum for OrderIDs 10010, 10011,10012,10013 should be 3 and not 1.Thanks
acadia
but Sign(Sum(Case When OD.OrderStatus = 2 Then 1 Else 0 End)) will always return 1 right?
acadia
You're grouping by OrderDate. So if you want at most 1 for each OrderDate, then SIGN will help. SIGN gives either 1, 0, or -1. So if you have three OrderStatus=2 for yesterday, none for today, and one for tomorrow, you'll have: yesterday, 1. today, 0. tomorrow, 1
Rob Farley
A: 

Rob Farley, Thanks but that is not exactly what I want. If there are 10 orders it should show 10 and not 1.

The sum I am doing is for all the orders in a day and not just one order.

Thanks again