如何在WHERE子句中使用CASE

时间:2014-10-31 13:43:47

标签: tsql

select 
    SUBSTRING(ackey,1,2) + '-' + SUBSTRING(ackey, 3,3) + '-' + SUBSTRING(ackey,8,6)
from 
    tHE_Move
where case 
        when acDocType in ('1900', '1910', '1920', '1930') then acWayOfSale <> 'E'
        when acDocType in ('1950', '1960') then acWayOfSale <> 'U'

我可以这样做吗?

我用以下方法解决了这个问题:

select 
    SUBSTRING(ackey,1,2) + '-' + SUBSTRING(ackey, 3,3) + '-' + SUBSTRING(ackey,8,6)
from 
    tHE_Move
where 
    (case when acDocType in ('1900', '1910', '1920', '1930') then acWayOfSale end <> 'E'
    or
    case when acDocType in ('1950','1960') then acWayOfSale end <> 'U')

但我感兴趣的是,如果只能在一个案例中解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你可以:

where acWayOfSale <> case when acDocType in ('1900', '1910', '1920', '1930') then 'E'
                     when acDocType in ('1950', '1960') then 'U'
                     else ...
                     end

(或者当然创建/修改一个包含acDocType值和所需字符以及JOIN的表格的表格

答案 1 :(得分:0)

你正在走上正轨,但是CASE会返回一个表达式而在tsql中不能返回一个布尔值。你真正想做的是使用AND和{{OR的组合1}}。在你的情况下:

where (acDocType in ('1900', '1910', '1920', '1930') and acWayOfSale <> 'E')
or (acDocType in ('1950','1960') and acWayOfSale <> 'U')