大家好我如何选择所有第二个最后一笔交易。
交易日志
------------------------------
ID|MemberName|TransactionDate|
------------------------------
1 |Member 1 |1/1/2017 |
------------------------------
2 |Member 1 |1/2/2017 | <- I want to select this transaction
------------------------------
3 |Member 1 |1/3/2017 |This the last transaction of this client
------------------------------
4 |Member 2 |2/1/2017 |
------------------------------
5 |Member 2 |2/2/2017 |<- I want to select this transaction
------------------------------
6 |Member 2 |2/3/2017 |This the last transaction of this client
我想选择所有客户的所有第二个到最后一笔交易。
答案 0 :(得分:1)
尝试ROW_NUMBER()
功能(除非您使用MySQL)。
SELECT A.ID, A.MEMBERNAME, A.TRANSACTIONDATE
FROM
(
SELECT ID, MEMBERNAME, TRANSACTIONDATE, ROW_NUMBER() OVER (PARTITION BY MEMBERNAME ORDER BY TRANSACTIONDATE DESC) AS RNUM
FROM TRANSACTION_TABLE
) A
WHERE A.RNUM = 2;
它为每种类型的Membername中的所有条目创建索引,并按降序排序编号(意味着第一个索引代表最新的transactiondate)。在此索引列中,您可以为第二个最后一个transactiondate提供rnum = 2的过滤器。
答案 1 :(得分:0)
Select top(1) a.Id,a.MemberName, a.TransactionDate from (select top(2) Id,MemberName,TransactionDate from Transaction_log order by Id desc) as a order by a.Id asc;
假设表名为Transaction_Log。 我希望这对你有用。
答案 2 :(得分:0)
我刚刚使用聚合和加入,如下面的查询所示:
SELECT A.* FROM TRANSACTION_LOG A INNER JOIN
(SELECT MEMBER_NAME, MAX(ID) ID FROM TRANSACTION_LOG
GROUP BY MEMBER_NAME) B
ON A.MEMBER_NAME=B.MEMBER_NAME AND A.ID=B.ID-1;