5
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 =(借方 - 贷方)

当我尝试为此创建另一列时,出现错误。

4

3 回答 3

8

只需添加:

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  
于 2012-07-23T19:53:49.043 回答
1

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

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

ALTER TABLE 表ADD NetCount integer ;

此处更新表名称SET NetCount=Debits-Credits ;

笔记:

  • 第一行添加一个名为 NetCount 的整数类型的列
  • 第二行将其更新为借方和贷方之间的差异
  • sql 命令用大写字母表示,特定于您的信息用斜体表示

祝你好运!

于 2014-07-09T15:29:04.830 回答
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
于 2012-07-23T19:55:48.527 回答