如何在同一列中添加正负总计

时间:2019-02-01 02:27:26

标签: sql-server tsql

我正在将SQL Server与名为dbo.over_short的表一起使用,并且试图找出如何从同一列中添加总计。

我有一列名为FINAL_OVER_SHORT_AMOUNT的列,其设计为十进制(10,2)。

在此字段中,存在正数(例如608.90),中性数(例如,例如0.00)和负数(例如,例如-608.90)。

是否可以将所有正数和所有负数(以负号开头的数字)分别相加。

要基本报告多少已结束和多少为负? (没有负数就减去正数。两个单独的总数)

select 
  ID,
  TRANSACTION_DATE,
  ASSOCIATE_ID,
  AGENCY_CODE,     
  FINAL_OVER_SHORT_AMOUNT
from
  dbo.over_short

任何帮助,将不胜感激!

3 个答案:

答案 0 :(得分:1)

您可以在此处使用条件聚合:

SELECT
    SUM(CASE WHEN FINAL_OVER_SHORT_AMOUNT >= 0
             THEN FINAL_OVER_SHORT_AMOUNT ELSE 0 END) AS pos_amount,
    SUM(CASE WHEN FINAL_OVER_SHORT_AMOUNT < 0
             THEN FINAL_OVER_SHORT_AMOUNT ELSE 0 END) AS neg_amount
FROM dbo.over_short;

您还可以将类似的查询与GROUP BY一起使用,假设您想要给定组/列的正/负总和,例如ID列。

答案 1 :(得分:1)

Sign是一个方便的小功能:

-- Sample data.
declare @Samples as Table ( Sample Decimal(10,2) );
insert into @Samples ( Sample ) values
  ( -10.00 ), ( -5.00 ), ( 0.00 ), ( 42.00 ), ( 8.00 );

-- Demonstrate separating values by sign.
select Sample,
  Sample * -Sign( Sign( Sample ) - 1 ) as Negative,
  Sample * Sign( Sign( Sample ) + 1 ) as Positive
  from @Samples;

-- Calculate the sums.
select Sum( Sample ) as Total,
  Sum( Sample * -Sign( Sign( Sample ) - 1 ) ) as NegativeTotal,
  Sum( Sample * Sign( Sign( Sample ) + 1 ) ) as PositiveTotal
  from @Samples;

答案 2 :(得分:1)

您可以使用此
select sum(case when FINAL_OVER_SHORT_AMOUNT>0 then FINAL_OVER_SHORT_AMOUNT else 0 end)as Positive, sum(case when FINAL_OVER_SHORT_AMOUNT<0 then FINAL_OVER_SHORT_AMOUNT else 0 end) as Negative from over_short
要么 您可以将结果存储在Temp表中并单独使用
select sum(case when FINAL_OVER_SHORT_AMOUNT>0 then FINAL_OVER_SHORT_AMOUNT else 0 end)as Positive, sum(case when FINAL_OVER_SHORT_AMOUNT<0 then FINAL_OVER_SHORT_AMOUNT else 0 end) as Negative into #Temp from [dbo].[Temp]

选择   sum(Positive)作为PositiveSum,sum(Negative)作为NegativeSum 来自#Temp