使用临时列的SQL Server WHERE子句

时间:2009-12-12 02:37:00

标签: sql sql-server tsql calculated-columns

我有以下查询,它使用CASE语句。 无论如何要添加到where子句WHERE IsBusinessDayFinal = 0?没有使用临时表?

非常感谢!

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].[AdminCalendar] ac LEFT JOIN
        [dbo].ProjectCalendar pc ON ac.DateTimeValue = pc.DateTimeValue AND pc.ProjectId = @projectId
    WHERE ac.DateTimeValue >= @startDate AND ac.DateTimeValue <= @finishDate;

3 个答案:

答案 0 :(得分:3)

使用

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

答案 1 :(得分:2)

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

答案 2 :(得分:2)

您可以使用COALESCE代替CASE,因为您正在检查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