在where条件中添加case语句,然后在then子句中提供条件语句

时间:2018-06-20 04:07:12

标签: sql sql-server case where-clause

我有一个where子句,我需要在其中添加case语句,并且必须在thenelse内给出条件语句。

我的状况看起来像这样

WHERE 
    CASE
        WHEN 
        Substring(datename(dw,getdate()),1,3) = 'mon' 
        THEN convert(varchar,dt_start,103) = convert(varchar,dateadd(day,-3,getdate()),103) 
        AND  convert(varchar,dt_start,103) <= convert(varchar,dateadd(day,-2,getdate()),103)
        ELSE convert(varchar,dt_start,103) = convert(varchar,dateadd(day,-1,getdate()),103)
    END  

但是此查询显示=then处的语法错误。相同的逻辑在PostgreSQL中有效,但是当我在SQL Server中尝试时,它在=处出现语法错误。我如何解决这个问题。请帮忙
 这是相应的PGSQL查询。

WHERE 
    CASE
        WHEN to_char(now(), 'dy'::text) = 'mon'::text THEN to_char(dt_start, 'yyyymmdd'::text) = to_char(now() - '3 days'::interval, 'yyyymmdd'::text) AND to_char(dt_start, 'yyyymmdd'::text) <= to_char(now() - '2 days'::interval, 'yyyymmdd'::text)
        ELSE to_char(dt_start, 'yyyymmdd'::text) = to_char(now() - '1 day'::interval, 'yyyymmdd'::text)
    END

2 个答案:

答案 0 :(得分:1)

  • 尝试

    WHERE 
    convert(varchar,dt_start,103)=
    CASE
        WHEN 
        Substring(datename(dw,getdate()),1,3) = 'mon' 
        THEN convert(varchar,dt_start,103) = 
        convert(varchar,dateadd(day,-3,getdate()),103) 
        ELSE convert(varchar,dt_start,103) = 
        convert(varchar,dateadd(day,-1,getdate()),103)
    END  
    
    AND
    
    convert(varchar,dt_start,103)<=
    CASE
     WHEN 
     Substring(datename(dw,getdate()),1,3) = 'mon' 
      then convert(varchar,dateadd(day,-2,getdate()),103)
      else
      --put a condition that does not filter any data (maybe)
      convert(varchar,getdate(),103)
      end
    

答案 1 :(得分:0)

请尝试:您必须根据自己的要求制定两个单独的条件,并记住其中一项,您只能以CASE的身份开始WHERE a = CASE,而不能以WHERE CASE ...THEN a = b+c ...身份开始 或在这种情况下,我建议您使用动态查询,在这种情况下,根据不同条件操作查询非常容易

WHERE convert(varchar,dt_start,103) =
    CASE WHEN Substring(datename(dw,getdate()),1,3) = 'mon' THEN 
        convert(varchar,dateadd(day,-3,getdate()),103) 
    ELSE 
        convert(varchar,dateadd(day,-1,getdate()),103) 
    END

    AND convert(varchar,dt_start,103) <= 
    CASE WHEN Substring(datename(dw,getdate()),1,3) = 'mon' THEN
        convert(varchar,dateadd(day,-2,getdate()),103)
    ELSE 
        convert(varchar,dt_start,103)
    END