SQL WHEN function - How to fix Syntax Error?

2019-07-30 14:52发布

I am new to SQL coding and I am encountering only one error code so far. At the second line WHEN CONVERT:

(rd.254 is my table date column)

CASE WHEN CONVERT(date,rd.F254) Between 
CONVERT(date,getdate()-7) AND CONVERT(date, getdate()-1) THEN rd.F64 END AS QtyLastWeek

WHEN CONVERT(date,rd.F254) <= CONVERT(date,getdate()-8) THEN rd.F64 END AS Qty2WeeksAgo

*Screenshot Here*

I am trying to find and fix the syntax.

3条回答
Ridiculous、
2楼-- · 2019-07-30 15:30

you have missing comma and case

CASE WHEN CONVERT(date,rd.F254) Between CONVERT(date,getdate()-7) AND CONVERT(date, getdate()-1) THEN 
   rd.F64 
END AS QtyLastWeek,
CASE WHEN CONVERT(date,rd.F254) <= CONVERT(date,getdate()-8) THEN 
   rd.F64 
END AS Qty2WeeksAgo
查看更多
老娘就宠你
3楼-- · 2019-07-30 15:33

There is incorrect syntax. If you want to select 2 columns QtyLastWeek and Qty2WeeksAgo you have to use the comma after QtyLastWeek and use another CASE expression.

SELECT 
    CASE WHEN CONVERT(date,rd.F254) BETWEEN CONVERT(date,getdate()-7) AND CONVERT(date, getdate()-1) THEN rd.F64 END AS QtyLastWeek,
    CASE WHEN CONVERT(date,rd.F254) <= CONVERT(date,getdate()-8) THEN rd.F64 END AS Qty2WeeksAgo
查看更多
虎瘦雄心在
4楼-- · 2019-07-30 15:33

You are missing case keyword in the second case statement. Try this !

CASE WHEN CONVERT(date,rd.F254) Between CONVERT(date,getdate()-7) AND CONVERT(date,getdate()-1) 
THEN rd.F64 
END AS QtyLastWeek,
CASE   WHEN CONVERT(date,rd.F254) <= CONVERT(date,getdate()-8) 
      THEN rd.F64 
END AS Qty2WeeksAgo
查看更多
登录 后发表回答