在SUM中查询CASE无法正常工作

时间:2015-08-24 07:35:14

标签: sql-server tsql

我应该总结一些时间段取决于开始和开始日期,我在SUM函数中使用了CASE。但查询不起作用,有什么问题? 这是查询:

SELECT @TotalDaysInThisYear = COALESCE(SUM(
                                CASE
                                    WHEN t.DateFrom < @BeginOfTheYear AND t.DateTo >= @EndOfTheYear THEN DATEDIFF(day, @BeginOfTheYear, t.DateTo) + 1
                                CASE
                                    WHEN t.DateFrom >= @BeginOfTheYear AND t.DateTo <= @EndOfTheYear THEN t.Days
                                CASE
                                    WHEN t.DateFrom <= @EndOfTheYear AND t.DateTo > @EndOfTheYear THEN DATEDIFF(day, t.DateFrom, @EndOfTheYear) + 1
                                ELSE 0
                                END
    ),0) FROM Common.TravelAgency ta JOIN Common.Travel t ON ta.TravelAgencyId = t.TravelId
    WHERE UserId = @UserId;

1 个答案:

答案 0 :(得分:0)

删除额外的CASE个关键字

 SELECT @TotalDaysInThisYear = COALESCE(SUM(
                                    CASE
                                        WHEN t.DateFrom < @BeginOfTheYear AND t.DateTo >= @EndOfTheYear THEN DATEDIFF(day, @BeginOfTheYear, t.DateTo) + 1
                                        WHEN t.DateFrom >= @BeginOfTheYear AND t.DateTo <= @EndOfTheYear THEN t.Days
                                        WHEN t.DateFrom <= @EndOfTheYear AND t.DateTo > @EndOfTheYear THEN DATEDIFF(day, t.DateFrom, @EndOfTheYear) + 1
                                    ELSE 0
                                    END
        ),0) FROM Common.TravelAgency ta JOIN Common.Travel t ON ta.TravelAgencyId = t.TravelId
        WHERE UserId = @UserId;