2016-12-19 33 views
-1

我正在根據case語句選擇列,並且想要根據case語句中返回的列使用where子句進行過濾。SQL Server其中條件基於所選案例列

Select 
    case 
     when UpdatedDate is not null 
      then UpdatedDate 
     when InsertedDate is not null 
      then InsertedDate 
     else VisitedDate 
    end 
From 
    tbl_UserTracking 
where 
    [UpdatedDate/InsertedDate/VisitedDate(based on case)] between date1 and date2 
+0

如果您沒有簡化問題,它可能會更好。如果每個日期列來自不同的表,並且這些值由於外部連接而可能爲NULL,那麼在連接邏輯和/或where子句中做什麼取決於數據和所需結果。請重新考慮提供更實際版本的問題。還包含樣本數據和預期結果。有關於如何提問的指南可以讓你獲得更好的結果。 –

回答

1

嘗試

SELECT * FROM 
( SELECT case when UpdatedDate is not null then UpdatedDate 
       when InsertedDate is not null then InsertedDate 
       else VisitedDate END AS DateColumn 
    FROM tbl_UserTracking 
) T 
WHERE DateColumn BETWEEN date1 AND date2 
+0

它不會給性能問題?因爲龐大的數據將從內部查詢返回,並帶有日期篩選。 – Gopinath

+0

*可能*不是。無論如何,我猜你會對此查詢進行表掃描或索引掃描。如果您擔心,請運行查詢分析器並查看查詢計劃。 –

0
SELECT COALESCE(UpdatedDate, InsertedDate, VisitedDate) AS DateColumn 
FROM tbl_UserTracking 
WHERE COALESCE(UpdatedDate, InsertedDate, VisitedDate) BETWEEN @date1 AND @date2 
+0

列是從不同的表和案件的條件也不同,我只是簡化條件.. – Gopinath

+0

@Gopinath你可以有COALESCE(T1.UpdatedDate,T3.InsertedDate,T8.VisitedDate) – JBrooks

0

使用coalesce()。這簡化了where條款:

Select coalesce(UpdatedDate, InsertedDate, VisitedDate) 
From tbl_UserTracking 
where coalesce(UpdatedDate, InsertedDate, VisitedDate) between date1 and date2; 

如果要定義一個變量,你可以使用CTE或子查詢。我喜歡指出橫向連接,它在SQL Server中使用apply關鍵字:

Select v.thedate 
From tbl_UserTracking t outer apply 
    (values (coalesce(UpdatedDate, InsertedDate, VisitedDate)) 
    ) v(thedate) 
where v.thedate between date1 and date2;