SQL中每个月的第一个值

我有一个包含带时间戳数据值的数据库,每天有多个样本,即

05/01/11 01:00:00 - 1.23  
05/01/11 01:12:34 - 0.99  
....  
05/01/11 23:59:59 - 2.34  
05/02/11 00:11:22 - 4.56

等等

我想获得每个月的第一个样本列表.我已经设法在每个月的第1天获得每个样本的列表:

SELECT
    "RecordTime", "FormattedValue"
FROM
    CDBHistoric
WHERE
    "Id" = 12345 AND EXTRACT (DAY FROM "RecordTime") = 1

这给出了类似的数据

03/01/11 00:00:01 - 1.23  
03/01/11 00:12:34 - 0.99  
....  
04/01/11 00:00:34 - 2.34  
04/01/11 00:11:22 - 4.56

但我无法获得每组的第一个值.

最佳答案 这是SQL Server的解决方案.这个想法是使用相关的子查询来识别

每年和每月的最小RecordTime.将这个想法转化为您的DBMS风格应该很容易.

WITH Data AS (
    SELECT CONVERT(DATETIME, '1-May-2011 01:00:00') AS RecordTime, 1.23 AS FormattedValue
    UNION ALL SELECT CONVERT(DATETIME, '1-May-2011 01:12:34'), 0.99
    UNION ALL SELECT CONVERT(DATETIME, '1-May-2011 23:59:59'), 2.34
    UNION ALL SELECT CONVERT(DATETIME, '2-May-2011 00:11:22'), 4.56
)
SELECT D1.*
FROM Data D1
WHERE D1.RecordTime = (SELECT MIN(RecordTime)
                       FROM Data D2
                       WHERE YEAR(D2.RecordTime) = YEAR(D1.RecordTime)
                       AND MONTH(D2.RecordTime) = MONTH(D1.RecordTime))

编辑:如果您的数据集很大,那么加入子查询应该会快得多,但可能更难转化为您的DBMS风格:

SELECT D1.*
FROM Data D1
INNER JOIN (
    SELECT MIN(D2.RecordTime) AS FirstMonthlyRecordTime
    FROM Data D2
    GROUP BY YEAR(D2.RecordTime), MONTH(D2.RecordTime)
) AS SubQuery
    ON D1.RecordTime = SubQuery.FirstMonthlyRecordTime

编辑2:以下代码是我上面第一个查询的标准SQL-92版本(在mySQL上测试):

SELECT T1.RecordTime, T1.FormattedValue
FROM CDBHistoric T1
WHERE T1.RecordTime = (SELECT MIN(T2.RecordTime)
                       FROM CDBHistoric T2
                       WHERE EXTRACT(YEAR FROM T1.RecordTime) = EXTRACT(YEAR FROM T2.RecordTime)
                       AND EXTRACT(MONTH FROM T1.RecordTime) = EXTRACT(MONTH FROM T2.RecordTime))
点赞