sql-servermaxdate

Filtering date after max date SQL


I have a table with values en date/timstamps. This table is dbo.meterdata.value. The output that i want to see is as followed: The latest date/timestamp (Max) but only the ones where te latest date/timestamp is last week. My Query is:

SELECT dbo.meter.DataImportCode
    ,dbo.meter.NAME
    ,dbo.company.NAME
    ,dbo.meter.MeterNumber
    ,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum'
    ,dbo.MeterOperator.Description
    ,dbo.meter.CumulativeReadings
FROM dbo.meter
LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID
JOIN DBO.Site ON dbo.meter.SiteID = dbo.site.SiteID
JOIN DBO.Company ON dbo.site.CompanyID = dbo.company.CompanyID
JOIN DBO.MeterOperator ON dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID
    --WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() )
    AND dbo.meterdata.RoundedTimeStamp IS NOT NULL
GROUP BY dbo.meter.DataImportCode
    ,dbo.company.NAME
    ,dbo.meter.NAME
    ,dbo.meter.MeterNumber
    ,dbo.MeterOperator.Description
    ,dbo.meter.CumulativeReadings

Example of the unfilterd result: Example

Thank you for help and support


Solution

  • Try the following:

    select dbo.meter.DataImportCode, dbo.meter.Name, dbo.company.Name, dbo.meter.MeterNumber,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum', dbo.MeterOperator.Description, dbo.meter.CumulativeReadings
    from dbo.meter
    LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID
    JOIN DBO.Site on dbo.meter.SiteID = dbo.site.SiteID
    JOIN DBO.Company on dbo.site.CompanyID = dbo.company.CompanyID
    JOIN DBO.MeterOperator on dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID
    --WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() )
    --AND dbo.meterdata.RoundedTimeStamp is not null
    GROUP BY dbo.meter.DataImportCode, dbo.company.name, dbo.meter.Name, dbo.meter.MeterNumber, dbo.MeterOperator.Description, dbo.meter.CumulativeReadings
    HAVING [laatste datum] < DateAdd(day,-7,GETDATE())
    

    If I understood you right, what you want to do is filter out the data after it has been grouped. This is done using the HAVING clause of the SELECT statement, as the above query depicts.