在带有日期参数的Where子句中使用CASE When

时间:2019-04-23 20:21:55

标签: sql

我正在尝试运行查询,并按日期参数限制某些帐户的交易。有人尝试过吗?在这种情况下我是否必须进行子选择?或者在where子句中可以使用案例?

我尝试使用它以防万一

 Select 

    Left(M.Account,4) As Entity, v.Type, isnull(round(-sum(t.debit+t.credit),2),'') As Activity

    From GLM_MASTER__ACCOUNT AS M CROSS APPLY 
    (Values (case  When right(m.account,9) = '1110.0130' then 'A'
                   When right(m.account,9) = '1110.0131' then 'F'
                   When right(m.account,9) = '1110.0132' then 'B'                 
                   When right(m.account,9) = '1110.0133' then 'C'
                   When right(m.account,9) = '2110.0061' then 'D'
                   When right(m.account,9) = '2110.0062' then 'G'
                   When Substring(m.account,6,3) >'000' and Substring(m.account,6,3) < '200' and right(m.account,9) between '3000.0000' and '3999.9999' then 'E'
                                                       When Substring(m.account,6,3) >'199' and Substring(m.account,6,3) < '300' and right(m.account,9) between '3000.0000' and '3999.9999' then 
                    Case 
                        When Substring(m.account,6,3) IN ('271','270') and Right(m.account,9) IN ('3150.0000') Then 'E' 
                        When Substring(m.account,6,3) IN ('271','270') and Right(m.account,9) Not IN ('3150.0000') Then 'G'
                        When Substring(m.account,6,3) NOT IN ('271','270') and right(m.account,9) between '3000.0000' and '3999.9999' Then 'E' End
                   When Substring(m.account,6,3) >'300' and right(m.account,9) between '3000.0000' and '3999.9999' then 'K'            
             End)
             ) v(type) 

    Left OUTER JOIN GLT_CURRENT__TRANSACTION AS T on M.Account = T.account 

    Where (Left(M.Account,4) IN (@Entity) OR '' IN (@Entity)) and
    T.DBID = 'ONNILIVE' and right(m.account,9) Not IN ('3910.0090','3910.0070') and v.type is not null
    and 
    Case When RIGHT(m.acount,9) = '1110.0130' then T.Accounting_Date <= Eomonth(SDate,-3) Else End 

    Group by Left(M.Account,4), Type

1 个答案:

答案 0 :(得分:1)

Where T.Accounting_Date >= 
        Case When RIGHT(m.Account,9) = '1110.0130' Then DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 6, 0) 
             When RIGHT(m.account,9) = '1110.0131' Then DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 6, 0) 
             When RIGHT(m.account,9) = '2110.0061' Then DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 6, 0) 
             When RIGHT(m.account,9) = '2110.0062' Then DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 6, 0) 
             When Right(m.account,9) Between '3000.0000' and '3999.9999' Then @SDate 
        End
And T.Accounting_Date <= @Edate