我有下表:
**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
现在我的问题是:
上面的sql安全使用吗?我只是依靠ORDER BY DESC关键字对TranDate进行排序,我不确定这是否非常可靠。
如何选择两个余额(第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
非常感谢!
答案 0 :(得分: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;
或者这可以使用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