按组总计

时间:2016-04-12 21:32:27

标签: sql-server tsql group-by sum

我有这个查询

select 
    TransDate, 
    sum(Amount) as total, 
    TransType, 
    Provider, 
    Client 
from @combined 
where Amount <> 0.00 
group by TransDate, TransType, Provider, Client, Amount 
order by Client asc

生成此结果集:

TransDate   total   TransType Provider   Client 

2014-08-12  5.00       I        FPCH    John Smith
2014-08-12  27.00      I        FPCH    John Smith
2014-08-12  -27.00     P        FPCH    John Smith
2014-08-12  -5.00      P        FPCH    John Smith 
2014-10-14  27.00      I        FPCH    John Smith
2014-10-14  -27.00     P        FPCH    John Smith
2013-02-23  5.00       I        FPCH    Abbie Smith
2013-02-23  -5.00      P        FPCH    Abbie Smith

我要做的是将相应的正数和负数相加,取消两个数字,然后在客户端上分组。

所以基本上这两个客户端都不会显示在列表中。

1 个答案:

答案 0 :(得分:0)

假设&#34;名称&#34;实际上是在每一行上重复并且是唯一的...(意味着唯一地标识需要一起求和的记录)

SELECT sum(2ndColumn), Name
FROM TableOrViewName
GROUP BY Name
HAVING sum(2ndColumn) <> 0

或者......如果您需要那些没有净化为0的数据

With CTE AS (
select TransDate, sum(Amount) as total, TransType, Provider, Client,
SUm(Amount) over (Partition by name Order by Name) ToInclude
from @combined where Amount <> 0.00 
group by TransDate, TransType, Provider, Client, Amount )

Select * from cte 
where ToInclude <> 0
order by Client asc