选择Max Date,然后在WHERE子句中使用它

时间:2015-08-18 15:32:53

标签: sql sql-server sql-server-2012

我确信这有一个简单的解决方案,但我在这里试图解决它的问题。有时额外的一双眼睛可以挽救这一天!

SELECT S.StoreId, MAX(AL.ActivityDate) AS LastActivity FROM Stores S
INNER JOIN dbo.ActivityLog AL ON AL.StoreID = S.StoreID
WHERE S.StoreID IN (SELECT StoreID FROM Stores WHERE Status = 2)
AND AL.ActivityDate < DATEADD(DAY, -180, GETDATE())
GROUP BY S.StoreID
ORDER BY LastActivity

我的目标:拉出所有MAX活动日期超过6个月(180天)的商店。这段代码似乎没有做到这一点......任何想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

我认为您可以使用group byhaving

执行您想要的操作
select al.StoreId, MAX(al.ActivityDate) AS LastActivity
from dbo.ActivityLog al
group by al.StoreId
having MAX(al.ActivityDate) < DATEADD(day, -100, getdate());