如何删除select query over子句中的重复记录

时间:2015-10-07 10:42:41

标签: sql-server over-clause

我在SQL SERVER中使用Transactions表,如下所示。

 UserID       TranDate     Amount
    1   |   2015-04-01   |  0
    1   |   2015-05-02   |  5000
    1   |   2015-09-07   |  1000
    1   |   2015-10-01   |  -4000
    1   |   2015-10-02   |  -700
    1   |   2015-10-03   |  252
    1   |   2015-10-03   |  260
    1   |   2015-10-04   |  1545
    1   |   2015-10-05   |  1445
    1   |   2015-10-06   |  -2000

我想查询此表以获取任何特定日期的可用余额。所以我使用了Windowing函数。

SELECT TransactionDate, 
    SUM(Amount) OVER (PARTITION BY UserId ORDER BY TransactionDate ROWS 
BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM Transactions

但由于交易表在2015-10-03日期有重复条目,因此重复2015-10-03日期的数据。每当有相同的日期时,我期待该日期的最后一次记录,总结可用余额。

当前输出

TransactionDate     AvailableBalance
   2015-04-01      |       0
   2015-05-02      |       5000
   2015-09-07      |       6000
   2015-10-01      |       2000
   2015-10-02      |       1300
   2015-10-03      |       1552
   2015-10-03      |       1804
   2015-10-04      |       3349
   2015-10-05      |       4794
   2015-10-06      |       2794

预计:我想从上面的结果集中删除以下记录。

   2015-10-03      |       1552

HERE是我的小提琴

2 个答案:

答案 0 :(得分:4)

您可以在窗口函数之前SUM

<强> SqlFiddleDemo

WITH cte AS
(
  SELECT TransactionDate, UserId, SUM(Amount) AS Amount
  FROM Transactions
  GROUP BY TransactionDate, UserId
)
SELECT TransactionDate,  
        SUM(Amount) OVER (PARTITION BY UserId ORDER BY TransactionDate ROWS 
    BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS AvailableBalance 
FROM cte

答案 1 :(得分:1)

使用RANGE代替ROWS

SQL Fiddle

SELECT
  TransactionDate,  
  SUM(Amount) OVER (
    PARTITION BY UserId 
    ORDER BY TransactionDate 
    RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS AvailableBalance
FROM Transactions;

此变体生成与最初请求不同的结果集,但在某些情况下可能有用。此变量返回与Transactions表中相同的行数。因此,它会返回两行2015-10-03,但对于AvailableBalance行,1804行。RANGE

我只是想突出显示有{{1}}选项。如果你真的每天需要一行,那么首先按照@ lad2025的答案按天分组是可行的。