在最大日期SQL之后过滤日期

时间:2018-04-02 13:19:33

标签: sql-server maxdate

我有一个带有日期/时间戳的值的表。该表是dbo.meterdata.value。我想看到的输出如下:最新的日期/时间戳(最大),但只有最新的日期/时间戳是上周。我的查询是:

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

感谢您的帮助和支持

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

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())

如果我理解正确,您要做的就是在 分组后过滤掉数据。这是使用HAVING语句的SELECT子句完成的,如上面的查询所示。