[英]SQL: Subtract two columns
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
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
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
晚上好。 我有一個類似的任務,發現只是添加一個列並更新它是非常短的。
我認為這可以在您的代碼生成數據庫之后完成。 如果它不適合您的情況,我將不勝感激。
ALTER TABLE 這里的表名是 ADD NetCount 整數 ;
此處更新表名稱 SET NetCount = Debits-Credits ;
筆記:
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.