我应该总结一些时间段取决于开始和开始日期,我在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;
答案 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;