日期和日期范围计算

时间:2015-05-12 21:50:20

标签: sql-server

我正在使用Sql Server 2012。

这是我计算订单中失败率的方式:

31天表1查询

sum(CASE 
WHEN (datediff(dd,serDATE,'2015-01-21')) >= 31 THEN 31
WHEN (datediff(dd,serDATE,'2015-01-21')) < 0 THEN 0
ELSE (datediff(dd,serDATE,'2015-01-21'))END) as 31days

1。如何在Datediff中动态循环和传递日期?

31次失败表2查询

SUM(Case when sometable.FAILUREDATE BETWEEN dateadd(DAY,-31,CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102)) 
AND CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102)Then 1 Else 0 END) As Failures31,

31天校准(公式)

((365*(Convert(decimal (8,1),T2.Failures31)/T1.31day))) [31dayCal]

对特定订单执行此操作时效果正常。

我希望在明天和月份之间进行类似的计算。

2。我应该采用什么方法来实现日常和月度计算?

我还有一个名为Calender的表,其中包含我可以使用的日期列表。

我真的很感激有关这方面的任何帮助。谢谢你..

1 个答案:

答案 0 :(得分:0)

<强>解决方案

 DECLARE @StartDate date = 'Jan 1, 2015'
    DECLARE @EndDate   date = DATEADD(DAY, 30, @StartDate)

    ;WITH cte AS (
        SELECT      @StartDate  AS ReportDate
        UNION ALL
        SELECT      DATEADD(DAY, 1, ReportDate)
        FROM        cte
        WHERE       ReportDate < @EndDate
    )

    Select T1.[date],T1.Fail31,T2.days31,
    ((365*(Convert(decimal (8,1),T1.Fail31)/T2.days31))) [31Fly]

    from 
    (
    SELECT cte.ReportDate as [date],

    SUM(Case when HISTORY.FAILUREDATE BETWEEN dateadd(DAY,-31,CONVERT(DATETIME, cte.ReportDate, 102)) 
    AND CONVERT(DATETIME, cte.ReportDate, 102)Then 1 Else 0 END) As Fail31

        FROM HISTORY left JOIN UNIT ON HISTORY.UNIT = UNIT.UNIT

        CROSS JOIN cte

        WHERE 

          UNIT.INSV_DATE < cte.ReportDate 
                    AND UNIT.MODEL in('Toyota')
                    AND(UNIT.Customer in('Jona' ))

                    group by 

                    cte.ReportDate  ) T1

                    Inner Join 

                    (SELECT cte.ReportDate as [date1],


    COUNT(UNIT.UNIT)  As Units,

     sum(CASE 
    WHEN (datediff(dd,INSV_DATE,cte.ReportDate)) >= 31 THEN 31
    WHEN (datediff(dd,INSV_DATE,cte.ReportDate)) < 0 THEN 0
    ELSE (datediff(dd,INSV_DATE,cte.ReportDate))END) as days31

        FROM UNIT

        CROSS JOIN cte

        WHERE 

          UNIT.INSV_DATE < cte.ReportDate 
                    AND UNIT.MODEL in('Toyota')
                    AND(UNIT.Customer in('Jona' ))

                    group by 

                    cte.ReportDate
    ) T2 on T1.[date] = t2.[date1]
                    Order by [date]