获取与每个日期范围的条件匹配的行数

时间:2013-03-20 22:04:55

标签: sql-server pivot

如何获得如下所示的结果。 我的查询应接受 current date 作为输入参数。

结果:

               (Prior 7 - 12 Months)     (Prior 4 - 6 Months)      (Current - 3 Months)
Analysis       3/23/2012-09/20/2012      09/21/2012-12/19/2012      12/20/2012-3/20/2013

Total Active         2                         0                             0

生成**Total active**的部分已完成,如下所示。

;WITH x AS 
    (
        SELECT  ID,statusdate,status , row_number() over (partition by ID order by statusdate DESC )  as RN1
        FROM 
            (SELECT ID,statusdate,status,
                   rn = row_number() over (partition by ID order by statusdate ) 
            FROM tblHistory   (nolock)
             WHERE [statusdate] <=  '20120920' AND
             ID in ('2145','2146','4145''7175')
            )  AS A
     )

SELECT  Count(*)  
FROM x 
WHERE rn1 = 1 AND status IN ('Backup','Active')

数据:

    ID      StatusDate              Status  Order
    2145    2012-04-29              n/a     1
    2145    2012-08-02              Backup  2
    2145    2012-11-09              Active  3
    2145    2012-11-12              Backup  4
    2145    2012-12-13              Pending 5
    2145    2012-12-18              Sold    6
    2146    2012-10-15              Pending 1
    2146    2012-10-15              n/a     2
    2146    2012-12-19              Sold    3
    4145    2012-04-24              Active  1
    4145    2012-04-24              Active  2
    4145    2012-05-22              Pending 3
    4145    2012-09-13              Active  4
    4145    2012-09-13              Active  5
    4145    2012-12-05              Pending 6
    4145    2012-12-19              Sold    7
    7175    2012-11-08              n/a     1
    7175    2012-12-01              Backup  2
    7175    2012-12-05              Active  3
    7175    2012-12-06              Pending 4
    7175    2012-12-19              Sold    5

2 个答案:

答案 0 :(得分:0)

使用GROUP BY功能,按日期分组。

将您选择的结尾更改为:

SELECT  [statusdate], Count(*) 
FROM x 
WHERE
    rn1 = 1
    AND status IN ('Backup','Active')
    AND [statusdate] IN ('2012-09-20', '2012-12-19' , '2013-03-20')
GROUP BY [statusdate]

答案 1 :(得分:0)

我会像这样使用案例陈述:

SELECT
    SUM(CASE WHEN DATEDIFF(month, statusdata, @current_date) BETWEEN 7 AND 12 
        THEN 1 ELSE 0 END) AS 'Prior7to12',
    SUM(CASE WHEN DATEDIFF(month, statusdata, @current_date) BETWEEN 6 AND 4 
        THEN 1 ELSE 0 END) AS 'Prior4to6',
    SUM(CASE WHEN DATEDIFF(month, statusdata, @current_date) BETWEEN 3 AND 0 
        THEN 1 ELSE 0 END) AS 'Prior0to3',
    FROM SomeTable

这将为您提供三列,分别为0-3,4-6和7-12个月。