一般用法为:
select case 1 when 1 then ‘yes’ when 2 then ‘no’ end
即为:when 1=1 取 ‘yes’
when 1=2 取 ‘no’
多条件为:
SELECT CASE WHEN 1=2 THEN 2 when 3=3 then 3 ELSE 4 end
case后不带参数,when可作多个条件
带语句使用:
–若是一次部门,输出第一次下订单日期,若是二次部门等,输出第一次分配客户日期
SELECT md.DepartName,a.UserName,CASE(md.DepartType)
WHEN ‘first’
THEN (SELECT MIN(orderdate) FROM bdOrder bo WHERE bo.SalesStaff=a.Account )
ELSE (SELECT MIN(opendate) FROM bdCustomerAllocate bca WHERE bca.SalesStaff =a.Account ) END
FROM frmuser a(NOLOCK)
JOIN mdDepartment md ON a.DepartmentId = md.ID
注: THEN 后面是一个值,故SELECT要用括号括起来。