Case和when Statement中的问题

时间:2015-12-26 08:24:58

标签: sql sql-server sql-server-2008

我对[self presentViewController:photoVC animated:YES completion:^{ photoVC.images = images; photoVC.index = index; photoVC.view.backgroundColor = [UIColor lightGrayColor]; }]; Case语句有疑问。我有两个transstypeid的列表,如10和12。

我尝试采取sale1金额,如果transstypeid 11有一笔金额!= 0表示,我需要减去转换金额10的金额

我尝试了很多,但没有任何效果。

我尝试了这些查询

when

3 个答案:

答案 0 :(得分:1)

尝试使用此SQL代码计算sale1:

CASE WHEN 
    SUM(CASE WHEN ct.TransTypeID = 11
        THEN ct.OVAmount - ct.OVDiscount
        ELSE 0 END) != 0
    THEN
        SUM(CASE WHEN ct.TransTypeID = 11
            THEN ct.OVAmount - ct.OVDiscount
            ELSE O END)
        - SUM(CASE WHEN ct.TransTypeID = 10
              THEN ct.OVAmount - ct.OVDiscount
              ELSE 0 END)
    ELSE 0 END

答案 1 :(得分:1)

我不确定我理解你的需要。但是,因为你赶时间,我试试看。

这样的事,也许?

select 
    CT1.CustomerCode, C.CustomerName,
    sale1 = 
    case 
        when ( sum(ct1.OVAmount  - ct1.OVDiscount) != 0 )
            then sum( ct1.OVAmount  - ct1.OVDiscount ) - sum( ct2.OVAmount - ct2.OVDiscount ) 

        else 
            0 
    end,
    C.CountryCode, C.CityCode 
from 
    Customers c
    Inner join CustomerTransactions CT1 ON ( CT1.CustomerCode = C.CustomerCode ) And ( ct1.TransTypeID = 11 )
    Inner join CustomerTransactions CT2 ON ( CT2.CustomerCode = C.CustomerCode ) And ( ct2.TransTypeID = 10 )
where 
    ( ct1.TransDate >= '2015-01-01' )
    and ( ct1.TransDate < '2016-01-01' )
    and ( ct2.TransDate >= '2015-01-01' )
    and ( ct2.TransDate < '2016-01-01' )
group by 
    ct1.CustomerCode,c.CustomerName,c.CountryCode,c.CityCode

答案 2 :(得分:1)

enter image description here

使用CTE:

with 
cte10 ( CustomerId, amount ) as ( 
    select 
        customerId, sum( amount ) as amount 
    from 
        CustomerTransaction 
    where 
        ( Type = 1 )
    group by CustomerId 
),
cte11 ( CustomerId, amount ) as ( 
    select 
        customerId, sum( amount ) as amount 
    from 
        CustomerTransaction 
    where 
        ( Type = 2 )
    group by CustomerId  
)
select 
    c.Id, c.Description,
    sale1 = 
    case 
        when ( cte10.amount <> 0 )
            then cte10.amount - cte11.amount 

        else 
            0 
    end
from 
    Customer c
    Inner join cte10 on ( cte10.CustomerId = C.id )
    inner join cte11 on ( cte11.Customerid = C.id )

enter image description here