I've got some data that has a DeviceID
column, a scan time column and some other columns.
For each of the deviceIDs, I want to return only the most recent row based on the scan time.
I am trying to create this query so that I can use it as a view and report on the data.
The database is a Microsoft SQL Server database and I'm running the query from SQL Server 2014 Management Studio.
The closest I've gotten to getting this to work is this :
SELECT
DeviceID,
AVSolutionName,
DefinitionsUpToDate,
ScanningEnabled,
Expired,
ScanTime
FROM
dbo.fact_AVSecurity
WHERE
(ScanTime IN (SELECT DISTINCT MAX(ScanTime) AS LastScan
FROM dbo.fact_AVSecurity AS Avs
GROUP BY DeviceID))
Unfortunately this is returning multiple values for the same ID.
ScanTime ScanningEnabled Expired DeviceID DefinitionsUpToDate AVSolutionName
10/12/2018 10:13 TRUE FALSE 15994 TRUE Webroot SecureAnywhere
4/12/2018 14:30 TRUE TRUE 15994 TRUE Webroot SecureAnywhere
What I'd like returned is just that first most recent row:
ScanTime ScanningEnabled Expired DeviceID DefinitionsUpToDate AVSolutionName
10/12/2018 10:13 TRUE FALSE 15994 TRUE Webroot SecureAnywhere
I've tried different approaches like : SQL - Returning only the most recent row
But can't seem to get them working. I'm not sure if it's something I'm doing wrong or if the specific brand of SQL I'm using doesn't do the "top 1" thing.
Is there a way to do what I'm after? How close am I with what I have?