I'm using SQL Server 2005. I have a payments table with payment id's, user id's, and timestamps. I want to find the most recent payment for each user. This is easy to search and find an answer for. What I also want to know though is if the most recent payment is the user's first payment or not.
I have the following which will number each user's payments:
SELECT
p.payment_id,
p.user_id,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date) AS paymentNumber
FROM
payment p
I'm not making the mental leap which then lets me then pick the highest paymentNumber per user. If I use the above as a subselect by using MAX(paymentNumber) and then grouping by user_id, I lose the payment_id which I need. But if I also add the payment_id into the group by clause, I'm back to one row per payment. I'm sure I'm overlooking the obvious. Any help?
6条答案
按热度按时间u0njafvf1#
试试这个:
ruarlubt2#
Do the same thing again.
Now the most recent payment has reversePaymentNumber 1, and the number of payments will be paymentNumber.
inb24sb23#
OP提供的查询完成了大部分工作。我们所需要做的就是将提供给
ROW_NUMBER()
的ORDER BY
子句改为降序,在降序点,最新记录的值将为1。我选择使用CTE是出于个人喜好--子查询也可以。6qfn3psc4#
一个不那么酷的方式我想
nr7wwzry5#
dluptydi6#
这样如何?