簡體   English   中英

SQL查詢返回兩個最近日期的記錄之間的差額

[英]SQL Query to return the difference between records of two most recent dates

我有下表:

**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    

非常感謝!

假定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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM