简体   繁体   中英

SQL Server : select max group by where date 2 years ago

For a stored procedure in sql server 2008 management studio i'm trying to build the following:

SELECT MAX(Orderdatum) AS Orderdatum, 
       klantnummer 
FROM   Klantenkaart 
GROUP BY klantnummer

this gives me the MAX orderdatum but this i want to combine with : orderdatum < DATEADD(YEAR, -2, SYSDATETIME())

So I want the selection of the records where max(orderdatum) = 2 years ago.

How can I do this?

Try this, Use having with group by

select MAX(Orderdatum)As Orderdatum, klantnummer from Klantenkaart 
 group by klantnummer
 having orderdatum < DATEADD(YEAR, -2, SYSDATETIME())

Check this :

SELECT 
 MAX(Orderdatum) AS Orderdatum, 
 klantnummer 
FROM Klantenkaart
 WHERE orderdatum > DATEADD(year,-2,GETDATE()) 
GROUP BY klantnummer

Just put your condition as a WHERE clause;

SELECT MAX(Orderdatum)As Orderdatum, klantnummer 
FROM   Klantenkaart 
WHERE  orderdatum < DATEADD(YEAR, -2, SYSDATETIME())
GROUP BY klantnummer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM