SQL:减去两列

时间:2012-07-23 19:52:06

标签: sql

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  

以上查询产生以下输出:

content_type_code_id    price   debits  credits
1                      0.00      317    0
1                      0.99      178    1
1                      1.99      786    1

但我想要这样的事情:

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

NetCount =(借方 - 贷方)

当我尝试为其创建另一列时,我收到错误。

3 个答案:

答案 0 :(得分:7)

只需添加:

SUM(case when price >= 0 THEN 1 ELSE 0 END) - 
    SUM(case when price < 0 THEN 1 ELSE 0 END) AS NetCount

作为你的最后一句话,所以你最终得到了这个:

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  

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  

答案 1 :(得分:1)

WITH tbl AS 
(
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  
)

SELECT content_type_code_id, proce, debits, credits, (debits - credits) netcount from tbl

答案 2 :(得分:1)

晚上好。我有一个类似的任务,发现只是添加一个列并更新它是非常短的。

我认为这可以在您的代码生成数据库之后完成。如果它对您的情况不起作用,我将不胜感激。

ALTER TABLE 此处的表名称 ADD NetCount 整数;

此处更新表格的名称 SET NetCount =借记 - 贷记;

注意:

  • 第一行添加一个名为NetCount的列,类型为整数
  • 第二行将其更新为借记和贷记之间的差异
  • sql命令是大写的,特定于您的信息是斜体
祝你好运!

相关问题