case when遇到空串轉成0,case空串

來源:互聯網
上載者:User

case when遇到空串轉成0,case空串
  需要注意:如果欄位為varchar類型,when後的條件要加上引號

SELECT (CASE 'marital_status' WHEN 0 THEN '已婚' WHEN 1 THEN '未婚' ELSE 'WEIZHI' END) AS marital_status  FROM tj_archive WHERE id='D1407280006'

用上面的語句,如果marital_status為空白串(而不是null)時,竟然查詢的結果為“已婚”

最後更改正確結果為:

SELECT (CASE 'marital_status' WHEN '0' THEN '已婚' WHEN '1'THEN '未婚' ELSE 'WEIZHI' END)AS marital_status FROM tj_archive WHERE id='D1407280006'


紅色部分為兩句的不同。


SQL使用CASE WHEN 行轉列為何會出現NULL值?

因為是男女分別統計,一般不這麼用
select --avg(總分), avg(case when 性別='男' then 總分 else 0 END) AS '男生的平均成績', avg(case when 性別='女' then 總分 else 0 END) AS '女生的平均成績'from students--GROUP BY 性別--這個group by去掉你試試

 
怎才可以將case when放入where中

不能放在where裡邊,像你這樣的,用子查詢去查會比較容易select * from where 欄位 in(select case when 欄位>1 then 1 else 0 end from 表)
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.