2014-10-31 134 views
0
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' 

我可以這樣做嗎?如何在WHERE子句中使用CASE

我解決了這個有:

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') 

但我有興趣,如果這隻能在一個情況下得到解決?

+1

你並不是真的需要'case' - 只需要用'AND'和'OR'將邏輯片段結合在一起。 'CASE'是爲了返回*值*的*表達式。 – 2014-10-31 13:46:10

回答

1

,你可以:

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

(或課程的創建/修改表與acDocType值與期望的性格和JOIN吧)

+0

謝謝。這是我需要:) – kole1108 2014-10-31 13:51:13

0

你在正確的軌道上,但CASE返回一個表達式,並在tsql中不能返回布爾值..你真正想要做的是使用ANDOR的組合。在你的情況下:

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

這也可以。謝謝。 – kole1108 2014-10-31 13:51:49