SQL QUERY ::条件在一列中

时间:2014-10-25 19:21:19

标签: sql

我希望在同一列上说明三个if / case条件

SELECT u.username, u.fullname, u.email, 
(IF u.status = "done" AND ui.itemtotal != "NULL" THEN 0 
IF u.status = "done" AND ui.itemtotal = "NULL" THEN 1 
IF u.status != "done" AND  ui.itemtotal != "NULL" THEN 2) AS "Item.Status"
         FROM 
         list_users u 
         JOIN list_items ui on ui.userid = u.id

1 个答案:

答案 0 :(得分:0)

使用CASE声明:

SELECT u.username, 
    u.fullname,
    u.email, 
    case when u.status = 'done' AND ui.itemtotal != 'NULL' then 0 
         when u.status = 'done' AND ui.itemtotal = 'NULL' then 1 
         when u.status != 'submitted' AND ui.itemtotal != 'NULL' then 2
    end as "Item.Status"
FROM 
    list_users u 
         JOIN list_items ui on ui.userid = u.id

检查NULL值时也要小心。我假设您正在检查NULL的字符串值。如果没有,请使用IS NULLIS NOT NULL

case when u.status = 'done' AND ui.itemtotal IS NOT NULL then 0 
     when u.status = 'done' AND ui.itemtotal IS NULL then 1 
     when u.status != 'submitted' AND ui.itemtotal IS NOT NULL then 2