SQL Server / T-SQL:选择特定间隔(分组依据)

时间:2011-10-18 16:26:44

标签: sql sql-server aggregate-functions aggregate

我想写一个聚合数据的选择(其ID为DATETIME列),理论上可能有任何间隔(如1小时,1小时和22秒,1年和3分钟等)。

此选择应该能够聚合1小时,12分钟,14秒并且应该返回3行

SELECT  DATEPART(YEAR,id) as year, 
        DATEPART(MONTH,id) as month,
        DATEPART(DAY,id) as day,
        DATEPART(HOUR,id) as hour,
        DATEPART(MINUTE,id) as minute,
        AVG([Open]),
        AVG([Close]),
        AVG([Min]),
        AVG([Max])
FROM QuoteHistory
where id between '2000-02-06 17:00:00.000' and '2000-02-06 20:36:42.000'
GROUP BY 
    DATEPART(YEAR,id), 
    DATEPART(MONTH,id),
    DATEPART(DAY,id),
    DATEPART(HOUR,id),
    DATEPART(MINUTE,id)
ORDER BY 1,2,3,4,5;

我有点被困在这里,无法解决这个问题。对于像“30分钟”这样的“简单间隔”,我可以添加一个模数

DATEPART(MINUTE,id)%2

但是当间隔“触及”超过日期的一部分时,我就被卡住了。

任何帮助表示感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

假设这里有一些参数:

;WITH Date_Ranges AS (
    SELECT
        @min_datetime AS start_datetime,
        DATEADD(SECOND, @seconds,
            DATEADD(MINUTE, @minutes,
            DATEADD(HOUR, @hours,
            DATEADD(DAY, @days,
            DATEADD(WEEK, @weeks,
            DATEADD(MONTH, @months,
            DATEADD(YEAR, @years, @min_datetime))))))) AS end_datetime
    UNION ALL
    SELECT
        DATEADD(SECOND, 1, end_datetime),
        DATEADD(SECOND, @seconds,
            DATEADD(MINUTE, @minutes,
            DATEADD(HOUR, @hours,
            DATEADD(DAY, @days,
            DATEADD(WEEK, @weeks,
            DATEADD(MONTH, @months,
            DATEADD(YEAR, @years, end_datetime)))))))
    FROM
        Date_Ranges
    WHERE
        DATEADD(SECOND, 1, end_datetime) < @max_datetime
)
SELECT
    DR.min_datetime,
    DR.max_datetime,
    AVG([Open]),
    AVG([Close]),
    AVG([Min]),
    AVG([Max])
FROM
    Date_Ranges DR
LEFT OUTER JOIN Quote_History QH ON
    QH.id BETWEEN DR.min_datetime AND DR.max_datetime
GROUP BY
    DR.min_datetime,
    DR.max_datetime
ORDER BY
    DR.min_datetime,
    DR.max_datetime

您可能需要摆弄如何处理边缘情况(根据您的数据,日期范围之间的1秒范围可能是个问题)。这应该有希望指出你正确的方向。