开发者

SQL Server WHERE Clause using Temporary Columns

开发者 https://www.devze.com 2022-12-13 17:21 出处:网络
I have the following query, which uses a CASE statement. Is there anyway to add into the where clause WHERE IsBusinessDayFinal = 0? without using a temporary table?

I have the following query, which uses a CASE statement. Is there anyway to add into the where clause WHERE IsBusinessDayFinal = 0? without using a temporary table?

thanks so much!

SELECT 
        ac.DateTimeValue,
        CASE 
            WHEN pc.IsBusinessDay IS NOT NULL THEN pc.IsBusinessDay
            ELSE ac.IsBusinessDay
        END AS IsBusinessDayFinal,
        ac.FullYear,
        ac.MonthValue,
        ac.DayOfMonth,
        ac.DayOfWeek,
        ac.Week 
    FROM 
        [dbo].[Admin开发者_Go百科Calendar] ac LEFT JOIN
        [dbo].ProjectCalendar pc ON ac.DateTimeValue = pc.DateTimeValue AND pc.ProjectId = @projectId
    WHERE ac.DateTimeValue >= @startDate AND ac.DateTimeValue <= @finishDate;


Use

WHERE (pc.IsBusinessDay IS NULL AND ac.IsBusinessDay = 0)
OR pc.IsBusinessDay = 0


WHERE ac.DateTimeValue >= @startDate AND ac.DateTimeValue <= @finishDate
      AND ((pc.IsBusinessDay IS NOT NULL AND pc.IsBusinessDay = 0) OR ac.IsBusinessDay = 0)


You can use COALESCE instead of CASE because you're checking for null:

SELECT ac.DateTimeValue,
       COALESCE(pc.IsBusinessDay, ac.IsBusinessDay) AS IsBusinessDayFinal,
       ac.FullYear,
       ac.MonthValue,
       ac.DayOfMonth,
       ac.DayOfWeek,
       ac.Week 
  FROM [dbo].[AdminCalendar] ac 
LEFT JOIN [dbo].ProjectCalendar pc ON ac.DateTimeValue = pc.DateTimeValue 
                                  AND pc.ProjectId = @projectId
WHERE ac.DateTimeValue >= @startDate 
 AND ac.DateTimeValue <= @finishDate
 AND COALESCE(pc.IsBusinessDay, ac.IsBusinessDay) = 0
0

精彩评论

暂无评论...
验证码 换一张
取 消