SQL Server其中condition基于所选的case列

时间:2016-12-19 23:47:56

标签: sql sql-server-2012

我正在根据case语句选择列,并希望根据case语句中返回的列过滤where子句。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

答案 2 :(得分: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;