如何在sql的时间范围内获取每个月的第一个和最后一个记录

时间:2014-12-05 07:52:17

标签: sql sql-server

我正在尝试使用sql获取给定日期范围内每个月的第一条记录和最后一条记录。我有一个示例代码,我刚刚选择了日期范围内的所有内容,现在我必须提取每个月的第一个和最后一个记录。

SELECT  PurOrderNum,
        OrderDate
FROM    Purchasing.PurOrder
WHERE   OrderDate >= '2013-02-28'
        AND OrderDate <= '2014-12-29'

1 个答案:

答案 0 :(得分:2)

您可以尝试row_number():

WITH FilterOrders AS (
    SELECT
    *
    , MinDatePrio = ROW_NUMBER() OVER (PARTITION BY YEAR(OrderDate), MONTH(OrderDate) ORDER BY OrderDate, PurOrderNum)
    , MaxDatePrio = ROW_NUMBER() OVER (PARTITION BY YEAR(OrderDate), MONTH(OrderDate) ORDER BY OrderDate DESC, PurOrderNum DESC)
    FROM Purchasing.PurOrder
    WHERE OrderDate BETWEEN '2013-02-28' AND '2014-12-29'
) SELECT PurOrderNum, OrderDate FROM FilterOrders
WHERE MinDatePrio = 1 OR MaxDatePrio = 1

<强>结果:

enter image description here