在SQL Server

时间:2016-07-28 00:28:26

标签: sql-server group-by sql-order-by aggregate-functions

我有一张这样的表:

ID ReceptionDate ResultFixedDateTime FinalMeasurementEndDateTime
----------------------------------------------------------------
1  2014-01-01    2014-01-01 10:20:35 2014-01-01 09:20:35
2  2014-01-01    2014-01-01 10:30:35 2014-01-01 09:40:35
3  2014-01-01    2014-01-01 10:50:35 2014-01-01 09:45:35
4  2014-01-02    2014-01-02 10:50:35 2014-01-02 09:45:35
5  2014-01-02    2014-01-02 10:50:35 2014-01-02 09:45:35

我需要一个类似下面的结果ReceptionDate的分组,具有相同ReceptionDate的记录的总计数和给定{{1的最大时差(ResultFixedDateTime - FinalMeasurementEndDateTime) }}

ReceptionDate

此查询返回的记录数量超出预期:

ReceptionDate Count      OperatingDiff
--------------------------------------
2014-01-01    3          65
2014-01-02    2          65

当我拿出

时,它会返回正确数量的记录
SELECT  
    ET.ReceptionDate,
    COUNT(ET.ReceptionDate),
    MAX(DATEDIFF(MINUTE, ET.ResultFixedDateTime, ET.FinalMeasurementEndDateTime)) AS OverTimeDiff
FROM 
    ExaminationTimes ET
WHERE 
    ET.ReceptionDate BETWEEN @StartDate AND @EndDate        
GROUP BY 
    ET.ReceptionDate, ET.ResultFixedDateTime, ET.FinalMeasurementEndDateTime
ORDER BY 
    ET.ReceptionDate

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

不要按ResultFixedDateTime&组分组最终的MeasurementEndDateTime

SELECT  ET.ReceptionDate, 
        COUNT(ET.ReceptionDate),
        MAX(DATEDIFF(MINUTE, ET.ResultFixedDateTime, ET.FinalMeasurementEndDateTime)) AS OverTimeDiff
        FROM ExaminationTimes ET
        WHERE ET.ReceptionDate BETWEEN @StartDate AND @EndDate      
        GROUP BY ET.ReceptionDate
        --,ET.ResultFixedDateTime
        --,ET.FinalMeasurementEndDateTime
        ORDER BY ET.ReceptionDate