在case语句中使用之间不起作用

时间:2014-07-03 01:49:15

标签: sql sql-server

我有以下查询来生成报告,使用它来检查日期是否在范围内。

由于某种原因,这不起作用,即使我输出数据时我知道它是正确的。

为什么它不起作用的任何想法?

这是我的SQL

SELECT @ReportDate 
SELECT DATEADD(dd, -1, @ReportDate), DATEADD(dd, -30, @ReportDate)

SELECT  i.Total, i.DateDue, c.Email, 
    CASE 
    WHEN i.DateDue BETWEEN DATEADD(dd, -1, @ReportDate) AND DATEADD(dd, -30, @ReportDate) THEN '1 - 30'
    WHEN i.DateDue BETWEEN DATEADD(dd, -31, @ReportDate) AND DATEADD(dd, -60, @ReportDate) THEN '31 - 60'
    WHEN i.DateDue BETWEEN DATEADD(dd, -61, @ReportDate) AND DATEADD(dd, -90, @ReportDate) THEN '61 - 90'
    WHEN i.DateDue BETWEEN DATEADD(dd, -91, @ReportDate) AND DATEADD(dd, -120, @ReportDate) THEN '91 - 120'
    ELSE '> 120' END
    AS [Group]
FROM    Data i 

数据结果:

ReportDate
2014-07-03 11:46:02.467

First Range
Start                   End
2014-07-02 11:46:02.467 2014-06-03 11:46:02.467

Total   DateDue                 Email                   Range
121535  2014-06-17 08:50:05.440 customer3@example.com   > 120
833208  2014-06-26 08:50:19.613 customer3@example.com   > 120
381400  2014-06-18 08:50:20.177 exmployee1@example.com  > 120

1 个答案:

答案 0 :(得分:3)

您的范围已反转 - BETWEEN左侧的日期始终右侧的日期之后。切换边以使查询按预期工作:

SELECT  i.Total, i.DateDue, c.Email, 
    CASE 
    WHEN i.DateDue BETWEEN DATEADD(dd, -30, @ReportDate) AND DATEADD(dd, -1, @ReportDate) THEN '1 - 30'
    WHEN i.DateDue BETWEEN DATEADD(dd, -60, @ReportDate) AND DATEADD(dd, -31, @ReportDate) THEN '31 - 60'
    WHEN i.DateDue BETWEEN DATEADD(dd, -90, @ReportDate) AND DATEADD(dd, -61, @ReportDate) THEN '61 - 90'
    WHEN i.DateDue BETWEEN DATEADD(dd, -120, @ReportDate) AND DATEADD(dd, -91, @ReportDate) THEN '91 - 120'
    ELSE '> 120' END
    AS [Group]
FROM    Data i