1

我有下表:

**TABLE1**

RecordID    UserID      UserName       Balance     TranDate
---------------------------------------------------------------
100         10001       John Doe       10213.00    2013-02-12 00:00:00.000
101         10001       John Doe        1932.00    2013-04-30 00:00:00.000
102         10001       John Doe       10213.00    2013-03-25 00:00:00.000
103         10001       John Doe       14514.00    2013-04-12 00:00:00.000
104         10001       John Doe        5430.00    2013-02-19 00:00:00.000
105         10001       John Doe       21242.00    2010-02-11 00:00:00.000
106         10001       John Doe       13342.00    2013-05-22 00:00:00.000

现在我要做的是查询最近的两个交易并得到这些数据:

RecordID    UserID      UserName       Balance     TranDate
---------------------------------------------------------------
106         10001       John Doe       13342.00    2013-05-22 00:00:00.000
101         10001       John Doe        1932.00    2013-04-30 00:00:00.000

然后使用上面的数据我想比较余额以显示差异:

UserID      UserName       Difference 
---------------------------------------------------------------
10001       John Doe       -11410.00

这只是显示了之前两个余额之间的差异(最新和最新之前的余额)

现在我在下面有以下查询。这可以显示两个最近的交易。

SELECT  
 TOP 2  *
  FROM  Table1
 WHERE  UserID  = '1001'
 ORDER
    BY  TranDate DESC

现在我的问题是:

  1. 上面的sql可以安全使用吗?我只是依靠 ORDER BY DESC 关键字对 TranDate 的排序,我不确定这是否非常可靠。

  2. 如何选择两个余额之间的差异(第 2 行 - 第 1 行)?我在网上寻找一些答案,我找到了关于自我加入的东西。我试过了,但它没有显示我想要的输出。

编辑:

这是我能得到的最接近我想要的结果。有人可以帮我解决这个问题吗?谢谢!

DECLARE @SampleTable TABLE
(
 UserID       INT,  
 UserName     VARCHAR(20),   
 Balance      DECIMAL(9,2) DEFAULT 0
)

INSERT 
  INTO  @SampleTable
       (UserID, UserName, Balance)
SELECT  
 TOP 2  UserID,
        UserName,
        Balance
  FROM  Table1
 WHERE  UserID  = '1001'
 ORDER
    BY  TranDate DESC


 SELECT  A.UserID,
         A.UserName,
         B.Balance - A.Balance AS Difference
   FROM  @SampleTable A
   JOIN  @SampleTable B
     ON  A.UserID  = B.UserID    

非常感谢!

4

1 回答 1

1

假设 SQL Server 作为 RDBMS,您应该能够使用类似以下内容:

;with cte as
(
  select recordid, userid, username, balance, trandate,
    row_number() over(partition by userid order by trandate desc) rn
  from table1 
) 
select c1.userid, c1.username,
  c1.balance - c2.balance diff
from cte c1
cross apply cte c2
where c1.rn = 1
  and c2.rn = 2;

请参阅带有演示的 SQL Fiddle

或者这可以在 row_number 值上使用 INNER JOIN 来完成:

;with cte as
(
  select recordid, userid, username, balance, trandate,
    row_number() over(partition by userid order by trandate desc) rn
  from table1 
) 
select c1.userid, c1.username,
  c1.balance - c2.balance diff
from cte c1
inner join cte c2
  on c1.rn + 1 = c2.rn
where c1.rn = 1

请参阅带有演示的 SQL Fiddle

于 2013-05-22T18:08:13.447 回答