select content_type_code_id 
    , ABS(price) AS price
    , SUM(case when price >= 0 THEN 1 ELSE 0 END) AS debits
    , SUM(case when price < 0 THEN 1 ELSE 0 END) AS credits
from dbo.transaction_unrated  
where transaction_date >= '2012/05/01'
      and transaction_date < '2012/06/01'
      and content_provider_code_id in (1)
group by content_type_code_id, ABS(price) 
ORDER BY ABS(price) ASC  
Run Code Online (Sandbox Code Playgroud)
以上查询产生以下输出:
content_type_code_id    price   debits  credits
1                      0.00      317    0
1                      0.99      178    1
1                      1.99      786    1
Run Code Online (Sandbox Code Playgroud)
但是我想要这样的东西:
content_type_code_id    price   debits  credits NetCount
    1                      0.00      317    0       317 
    1                      0.99      178    1       177 
    1                      1.99      786    1       785
Run Code Online (Sandbox Code Playgroud)
NetCount =(借方 - 贷方)
当我尝试为其创建另一列时,我收到错误.
只需添加:
SUM(case when price >= 0 THEN 1 ELSE 0 END) - 
    SUM(case when price < 0 THEN 1 ELSE 0 END) AS NetCount
Run Code Online (Sandbox Code Playgroud)
作为你的最后一句话,所以你最终得到这个:
select content_type_code_id 
    , ABS(price) AS price
    , SUM(case when price >= 0 THEN 1 ELSE 0 END) AS debits
    , SUM(case when price < 0 THEN 1 ELSE 0 END) AS credits
    , SUM(case when price >= 0 THEN 1 ELSE 0 END) - 
        SUM(case when price < 0 THEN 1 ELSE 0 END) AS NetCount
from dbo.transaction_unrated  
where transaction_date >= '2012/05/01'
      and transaction_date < '2012/06/01'
      and content_provider_code_id in (1)
group by content_type_code_id, ABS(price) 
ORDER BY ABS(price) ASC  
Run Code Online (Sandbox Code Playgroud)
Lamak的派生表格版本:
您还可以使用派生表使代码更清晰:
select content_type_code_id,
    price, debits, credits, (debits - credits) as NetCount
from (
    select content_type_code_id 
        , ABS(price) AS price
        , SUM(case when price >= 0 THEN 1 ELSE 0 END) AS debits
        , SUM(case when price < 0 THEN 1 ELSE 0 END) AS credits
    from dbo.transaction_unrated  
    where transaction_date >= '2012/05/01'
          and transaction_date < '2012/06/01'
          and content_provider_code_id in (1)
    group by content_type_code_id, ABS(price) 
) YourDerivedTable
ORDER BY price ASC  
Run Code Online (Sandbox Code Playgroud)