2009-12-12 121 views
2

我有以下查詢,它使用CASE語句。 無論如何要添加到where子句WHERE IsBusinessDayFinal = 0?不使用臨時表?SQL Server WHERE子句使用臨時列

非常感謝!

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; 
+1

您可以使用子查詢? – 2009-12-12 02:43:27

回答

3

使用

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

謝謝!我沒有意識到解決方案其實很簡單。我想我沒覺得夠辛苦。 = p – Abe 2009-12-12 02:59:39

+0

+1。即使邏輯是相同的,我更喜歡你的IS NULL版本! – 2009-12-12 04:10:15

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

可以使用COALESCE代替CASE,因爲你檢查空:

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