按总和分组,每个总和组使用Sql Server结束最后一行

时间:2018-06-25 06:16:27

标签: sql sql-server group-by tradingview-api

我已附加一张图像,我希望使用SQL Server查询基于下组最后一行的总和为7800-2000 = 5800 enter image description here

我想要这样的输出

GroupName     Credit    Debit   DrCrEffect  UnderGroupName  Total
Opening Balance 0.00    0.00    Dr         Master Group      NULL
Opening Stock   0.00    0.00    Dr         Opening Stock     NULL
Purchase        0.00    7800.00 Dr         Purchase          0.00 
Purchase Return 2000.00  0.00   Dr          Purchase         5800

查询:

SELECT MAG.GroupName,
    SUM(isnull(tm.Credit,0.00))Credit,
    SUM(ISNULL(TM.Debit,0.00))Debit,
    mag.DrCrEffect,
    MAG.UnderGroupName,
    SUM(TM.Credit-tm.Debit)Total
FROM dbo.Mst_Account_Group MAG
    LEFT JOIN  dbo.Party P ON MAG.Mst_Account_Group_Id = P.Mst_Account_Group_Id 
        AND mag.EffectTo='Trading Account' AND MAG.DrCrEffect='dr'
    LEFT JOIN  dbo.Transaction_Master TM ON tm.Ledger_Id=p.Party_Id
WHERE P.Company_Id=1 AND P.Branch_Id=1
GROUP BY mag.GroupName, mag.DrCrEffect, MAG.UnderGroupName 

1 个答案:

答案 0 :(得分:0)

您可以使用LAG函数来实现此目的。 LAG将为您提供当前行选择中上一行的值。

declare @table table (groupname varchar(50),
                      credit numeric(18,2),
                      debit numeric(18,2),
                      drcreffect varchar(50),
                      undergroup varchar(50))

insert into @table values
('Opening Balance', 0.00   , 0.00    ,'Dr',  'Master Group'   ),
('Opening Stock',   0.00   , 0.00    ,'Dr',  'Opening Stock' ),
('Purchase',        0.00   , 7800.00 ,'Dr',  'Purchase'),
('Purchase Return', 2000.00,  0.00   ,'Dr',  'Purchase')


select groupname,
       credit,
       debit,
       drcreffect,
       undergroup, 
       LAG(debit,1,0) OVER (ORDER BY groupname)-credit AS Total
from @table

输出:

Output

注意:将@table替换为您的实际表名。

更新

declare @table table (groupname varchar(50),
                      credit numeric(18,2),
                      debit numeric(18,2),
                      drcreffect varchar(50),
                      undergroup varchar(50))

insert into @table values
('Opening Balance', 0.00   , 0.00    ,'Dr',  'Master Group'   ),
('Opening Stock',   0.00   , 0.00    ,'Dr',  'Opening Stock' ),
('Purchase',        0.00   , 7800.00 ,'Dr',  'Purchase'),
('Purchase Return', 2000.00,  0.00   ,'Dr',  'Purchase'),
('Purchase Return', 3000.00, 0.00 ,'Dr', 'Purchase'),
('Sales', 0.00, 5000.00 ,'Dr', 'Sales'),
('Sales Return', 2000.00,  0.00   ,'Dr',  'Sales'),
('Sales Return', 2000.00, 0.00 ,'Dr', 'Sales')


SELECT groupname,credit,debit,drcreffect,undergroup, LAG(debit,1,0) OVER (ORDER BY groupname)-credit AS Total from (
SELECT DISTINCT groupname,SUM(credit) OVER(PARTITION BY groupname) AS Credit,SUM(debit) OVER(PARTITION BY groupname) AS debit,drcreffect,undergroup
FROM @table ) X