Terry
Terry

Reputation: 842

SQL sub select if exists

I am using SQL Server 2012. I have two tables to hold orders for products. Order which has a received date and OrderItem which has a price and order id fk.

I am trying to write a query get all orders within a date range, group them by the date, and then sum all the order items price to get the total of all orders for that date.

I have this working. Now I want to add another column to select the difference between the total price for that day, and 7 days ago. If there are no orders 7 days ago then the column should be null.

So at the moment I have the below query:

select cast(o.ReceivedDate as date) as OrderDate, 
coalesce(count(orderItems.orderId), 0) as Orders,
coalesce(sum(orderItems.Price), 0) as Price
from [Order] o

left outer join (
        select o.Id as orderId, sum(ot.Price) as Price
        from OrderItem ot
        join [Order] o on ot.OrderId = o.Id
        where o.ReceivedDate >= @DateFrom and o.ReceivedDate <= @DateTo
        group by o.Id
) as orderItems on o.Id = orderItems.orderId

where o.ReceivedDate >= @DateFrom and o.ReceivedDate <= @DateTo
group by cast(o.ReceivedDate as date)
order by cast(o.ReceivedDate as date) desc

So how can I add my other column to this query? I need to do something like:

//pseudo 
if o.RecievedDate - 7 exists then orderItems.Price - Price from 7 days ago else null

But I am not sure how to do this? I have created a sqlfiddle to help explain http://sqlfiddle.com/#!6/8b837/1

So from my sample data what I want to achieve is results like this:

|  ORDERDATE | ORDERS | PRICE |  DIFF7DAYS  |
---------------------------------------------
| 2013-01-25 |      3 |    38 |          28 |
| 2013-01-24 |      1 |    12 |        null |
| 2013-01-23 |      1 |    10 |        null |
| 2013-01-22 |      1 |    33 |        null |
| 2013-01-18 |      1 |    10 |        null |
| 2013-01-10 |      1 |     3 |         -43 |
| 2013-01-08 |      2 |    11 |        null |
| 2013-01-04 |      1 |     1 |        null |
| 2013-01-03 |      3 |    46 |        null |

As you can see, the 25th has a order 7 days ago so the difference is shown. The 24th doesn't so null is displayed.

Any help would be much appreciated.

Upvotes: 3

Views: 894

Answers (2)

flup
flup

Reputation: 27104

Use a temp table and join it on the datediff.

DECLARE @DateFrom datetime
SET @DateFrom = '2012-12-02'

DECLARE @DateTo datetime
SET @DateTo = '2013-03-13'

CREATE TABLE #temp ( orderdate date, orders int, price money)
INSERT INTO #temp
SELECT cast(o.ReceivedDate AS date) AS OrderDate,
coalesce(count(orderItems.orderId), 0) AS Orders,
coalesce(sum(orderItems.Price), 0) AS Price
FROM [Order] o

LEFT OUTER JOIN (
SELECT o.Id AS orderId, sum(ot.Price) AS Price
FROM OrderItem ot
JOIN [Order] o ON ot.OrderId = o.Id
WHERE o.ReceivedDate >= @DateFrom AND o.ReceivedDate <= @DateTo
GROUP BY o.Id
) AS orderItems ON o.Id = orderItems.orderId

WHERE o.ReceivedDate >= @DateFrom AND o.ReceivedDate <= @DateTo
GROUP BY cast(o.ReceivedDate AS date)

SELECT t1.orderdate, t1.orders, t1.price, 
t1.price - t2.price AS diff7days
FROM #temp t1 LEFT JOIN #temp t2
ON datediff(DAY, t2.orderdate, t1.orderdate) = 7
ORDER BY t1.orderdate DESC

http://sqlfiddle.com/#!6/8b837/34

Upvotes: 1

Kaf
Kaf

Reputation: 33809

Not sure why you are using a left outer join between [Orders] table and the subquery as there cannot be orders without order items (in general):

To get your results you could do it in a simplified version as below using a CTE

SQL-FIDDLE-DEMO

;with cte as (
  select convert(date,o.ReceivedDate) orderDate,
       count(distinct o.Id) as Orders,
       coalesce(sum(ot.Price),0) as Price
  from OrderItem ot
        join [Order] o on ot.OrderId = o.Id
  where o.ReceivedDate >= @DateFrom and o.ReceivedDate <= @DateTo
  group by convert(date,o.ReceivedDate)
)
select c1.orderDate, c1.Orders, c1.Price, c1.Price-c2.Price DIFF7DAYS
from cte c1 left join cte c2 on dateadd(day,-7,c1.orderdate) = c2.orderdate
order by c1.orderdate desc


|  ORDERDATE | ORDERS | PRICE | DIFF7DAYS |
-------------------------------------------
| 2013-01-25 |      3 |    38 |        28 |
| 2013-01-24 |      1 |    12 |    (null) |
| 2013-01-23 |      1 |    10 |    (null) |
| 2013-01-22 |      1 |    33 |    (null) |
| 2013-01-18 |      1 |    10 |    (null) |
| 2013-01-10 |      1 |     3 |       -43 |
| 2013-01-08 |      2 |    11 |    (null) |
| 2013-01-04 |      1 |     1 |    (null) |
| 2013-01-03 |      3 |    46 |    (null) |

Upvotes: 2

Related Questions