gpt4 book ai didi

SQL:减去两列

转载 作者:行者123 更新时间:2023-12-04 20:12:23 25 4
gpt4 key购买 nike

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

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

最佳答案

只需添加:

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

拉马克的派生表版本:

您还可以使用派生表使代码更简洁:
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

关于SQL:减去两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com