如何在聚合函数中添加原始数量的最旧事务?

时间:2018-01-30 13:13:00

标签: sql-server tsql sql-server-2014

我正在尝试找出如何将第一笔交易的原始金额(最早按发布日期)包含在汇总查询中。

以下查找已撤消的交易..

SELECT DISTINCT   
    [Account], [Voucher],
    [DocumentDate],
    SUM([Amount])   
FROM            
    MyTable 
WHERE           
    [Account] = 'abc'
GROUP BY
    [Account], [Voucher], [DocumentDate]
HAVING          
    SUM([Amount]) = 0

如何在每笔记录的最早发布日期的交易结果中包含金额?

例如,使用以下内容:

Account   Voucher   DocumentDate   PostedDate   Amount
---------------------------------------------------------
abc         1       01/01/2018     08/01/2018    100.00
abc         1       01/01/2018     15/01/2018   -100.00 

预期结果将是:

Account   Voucher   DocumentDate   OriginalAmount   Sum(Amount)   Records
-------------------------------------------------------------------------
abc          1      01/01/2018        100.00           0.00          2

2 个答案:

答案 0 :(得分:2)

一种方法是使用带有first_valuefixed:falsevar board = JXG.JSXGraph.initBoard('box1', {boundingbox: [-5, 20, 5, -2], axis:true}); var graph = board.create('functiongraph', [ function(x) { return Math.sin(x) + 5; }], {fixed: false}); 的cte。

首先,创建并填充样本表(在将来的问题中保存此步骤)

sum...over

cte:

count...over

查询:

DECLARE @T AS TABLE
(
    Account char(3),
    Voucher int,
    DocumentDate date,
    PostedDate date,
    Amount numeric(5,2)
)

INSERT INTO @T VALUES
('abc', 1, '2018-01-01', '2018-01-08', 100),
('abc', 1, '2018-01-01', '2018-01-15', -100)

结果:

;WITH CTE
AS
(
    SELECT  [Account], 
            [Voucher],
            [DocumentDate],
            FIRST_VALUE(Amount) OVER(PARTITION BY [Account], [Voucher], [DocumentDate] ORDER BY PostedDate) AS OriginalAmount,
            SUM([Amount]) OVER(PARTITION BY [Account], [Voucher], [DocumentDate]) AS [Sum(Amount)],
            COUNT(*) OVER(PARTITION BY [Account], [Voucher], [DocumentDate]) Records
    FROM            
        @T 
    WHERE           
        [Account] = 'abc'
)

See a live demo on rextester.

答案 1 :(得分:1)

看起来很简单......我错过了什么吗?

SELECT DISTINCT *
FROM CTE 
WHERE [Sum(Amount)] = 0