如何基于SQL CASE语句筛选WHERE条件中的记录

时间:2014-07-01 19:42:12

标签: sql sql-server operators case conditional-statements

我有以下用于加载代码表的case语句。我必须找到加载到代码表中的记录数 当[gli-src] ='8'

TRAN_CODE = 7
INSERT INTO codes 
    SELECT CASE 
             WHEN [cash-amt] > 0 THEN '1' 
             WHEN [prod-n] = '42' 
                  AND [tran-code] IN ( '-1', '-2', '-3' ) THEN '17' 
             WHEN [gli-src] = '8' THEN '7' 
             WHEN [prod-n] = '42' 
                  AND [gli-src] = 'L' 
                  AND [tran-code] IN ( '1', '2', '3' ) THEN '7' 
             WHEN [gli-src] = 'L' 
                  AND [prod-n] = '60' 
                  AND [tran-code] IN ( '4', '5', '6' ) THEN '7' 
             ELSE '4' 
           END AS TRAN_CODE 
    FROM   txn 

这是我试过的,虽然我很困惑如何过滤掉其他情况。

select COUNT(1) from  txn
where [CASH-AMT] <= 0 
and
.
.
.
. ????
and [gli-src] = '8'

1 个答案:

答案 0 :(得分:0)

SELECT COUNT(1)
FROM (  SELECT CASE 
                 WHEN [cash-amt] > 0 THEN '1' 
                 WHEN [prod-n] = '42' 
                      AND [tran-code] IN ( '-1', '-2', '-3' ) THEN '17' 
                 WHEN [gli-src] = '8' THEN '7' 
                 WHEN [prod-n] = '42' 
                      AND [gli-src] = 'L' 
                      AND [tran-code] IN ( '1', '2', '3' ) THEN '7' 
                 WHEN [gli-src] = 'L' 
                      AND [prod-n] = '60' 
                      AND [tran-code] IN ( '4', '5', '6' ) THEN '7' 
                 ELSE '4' 
               END AS TRAN_CODE, 
               [CASH-AMT],
               [gli-src]
        FROM   txn) AS T
WHERE [CASH-AMT] <= 0 
AND [gli-src] = '8'
AND TRAN_CODE = 7