SQL Group by和相同的帐号

时间:2019-04-15 13:17:39

标签: sql sql-server sql-server-2008

我确实具有如下表格结构

enter image description here

我的要求是我必须按帐号和描述进行分组,并显示如下总金额

enter image description here

我尝试为小组写信

SELECT AC_NUMBER, AC_NAME, SUM(ISNULL(DEBIT,0)) DEBIT, SUM(ISNULL(CREDIT,0)) CREDIT
FROM AC_TRANSACTION
GROUP BY AC_NUMBER, AC_NAME

,但帐户号码1234-00总计为总计,并显示在以下一行中 enter image description here

基本上,Trasnaction_id与第一个表绑定在一起。 顺序中第一个表的交易ID为3344,3345,3355,3356,3467,3468,4123,4124,像这样

每次创建2笔交易,其中一笔是BOA交易,其他说明 因此,如果您通过transaction_id进行订购,您将获得上面的第一个表订单 我们如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果表中有identity_field: 示例:

DECLARE @A table ( identity_field int identity(1,1),prod_id NVARCHAR(10) , v int)
INSERT into @A(prod_id,v)
VALUES('A',10),('A',20),('B',30),('A',40),('B',50),('B',60),('B',70),('A',80),('C',90);

WITH A AS (
select row_number()over (order by prod_id,identity_field) nr,*
from @A)
,B AS(
SELECT identity_field-nr group_field,*
FROM A
)
select MIN(identity_field) tran_id,prod_id, SUM(v) sum_v
FROM B
GROUP BY prod_id,group_field
order by MIN(identity_field)

您的桌子:

WITH A AS (
select identity_field-row_number()over (order by ACCOUNT_NUMBER,DESCRIPTION,identity_field) group_field,*
from YOUT_TABLE)

select MIN(identity_field) tran_id,ACCOUNT_NUMBER,DESCRIPTION, SUM(DEBIT) transact_debit,SUM(CREDIT) transact_credit
FROM A
GROUP BY ACCOUNT_NUMBER,DESCRIPTION,group_field
order by MIN(identity_field)