2

I am currently building a website where people can place orders so it's kinda like an online shop. I want to create a view where i can easily see which users have not placed an order for more than 90 days.

For this I have created this MS SQL View:

SELECT
    dbo.AspNetUsers.Id,
    dbo.AspNetUsers.FirstName,
    dbo.AspNetUsers.LastName,
    dbo.AspNetUsers.Email,
    dbo.AspNetUsers.Street,
    dbo.AspNetUsers.SignupDate,
    MAX(dbo.Orders.OrderDate) AS OrderDate 
FROM
    dbo.AspNetUsers 
INNER JOIN
    dbo.Orders 
        ON dbo.AspNetUsers.Id = dbo.Orders.OrderUserId 
GROUP BY
    dbo.AspNetUsers.Id,
    dbo.AspNetUsers.FirstName,
    dbo.AspNetUsers.LastName,
    dbo.AspNetUsers.Email,
    dbo.AspNetUsers.Street,
    dbo.AspNetUsers.SignupDate

Now this piece of code is still lacking the where-condition that checks if the date is older than 90 days. WHERE dbo.Orders.OrderDate < DATEADD(day, -90, GETDATE()). I tried adding it before the group by but this does not work (It should only check if the most recent order is older than 90 days and this would check if there is any order date that is older than 90 days).

So where can I put this condition to achieve the desired result?

Tim Gerhard
  • 3,477
  • 2
  • 19
  • 40

2 Answers2

4

Check aggregate conditions with having instead of where

GROUP BY ...
HAVING MAX(dbo.Orders.OrderDate) < DATEADD(day, -90, GETDATE())
juergen d
  • 201,996
  • 37
  • 293
  • 362
1

please try to use having clause

Ahmed Emad
  • 265
  • 2
  • 4