我正在使用SQL Server 2005.我有一个付款表,其中包含付款ID,用户ID和时间戳。我想找到每个用户的最新付款。这很容易搜索并找到答案。我还想知道的是,最近的付款是否是用户的第一次付款。
我有以下内容对每位用户的付款进行编号:
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
我没有进行精神上的飞跃,然后让我选择每个用户最高的paymentNumber。如果我使用MAX(paymentNumber)将上面的内容用作子选择,然后按user_id进行分组,则会丢失我需要的payment_id。但是,如果我还将payment_id添加到group by子句中,那么每次付款我都会返回一行。我敢肯定我忽视了这一点。有什么帮助吗?
答案 0 :(得分:28)
试试这个:
SELECT a.*, CASE WHEN totalPayments>1 THEN 'NO' ELSE 'YES' END IsFirstPayment
FROM(
SELECT p.payment_id,
p.user_id,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date DESC) AS paymentNumber,
SUM(1) OVER (PARTITION BY p.user_id) AS totalPayments
FROM payment p
) a
WHERE paymentNumber = 1
答案 1 :(得分:11)
再做同样的事情。
SELECT
p.payment_id,
p.user_id,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date) AS paymentNumber,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date DESC) AS reversePaymentNumber,
FROM
payment p
现在最近的付款有reversePaymentNumber 1,付款次数为paymentNumber。
答案 2 :(得分:3)
; with cte as (
SELECT
p.payment_id,
p.user_id,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date desc) AS paymentNumber
FROM
payment p
) select * from cte where paymentNumber = 1
答案 3 :(得分:1)
我认为不太酷的方式
; with maxp as
(
select
p.user_id,
max(p.payment_date) as MaxPaymentDate
from payment p
group by p.userid
),
nump as
(
select
p.payment_id,
p.user_id,
p.payment_date,
ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY p.payment_date) AS paymentNumber
FROM payment p
),
a as
(
select
nump.payment_id,
nump.user_id,
nump.paymentNumber
case when maxp.MaxPaymentDate is null then 'Old' else 'New' end as NewState
from nump
left outer join maxp
on nump.user_id=maxp.user_id
and nump.payment_date=maxp.MaxPaymentDate
)
select
*
from a
where NewState='New'
答案 4 :(得分:1)
SELECT * FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY OS.ContactId ORDER BY OS.Date ASC) AS FirstRow#,
ROW_NUMBER() OVER(PARTITION BY OS.ContactId ORDER BY OS.Date DESC) AS LastRow#,
OS.Contactid,CONVERT(VARCHAR,OS.Date,106) 'Purchase Month',
OS.ProductId 'MyCII Subscription/Directory', OS.Charges 'Amount(INR)',OS.Date 'RAWDate'
FROM tblOnlineServices OS
WHERE Date IS NOT NULL AND Contactid IN('C000013112','C000010859')
) FirstPurchase
WHERE FirstRow# = 1 OR LastRow# = 1
ORDER BY Contactid, RAWDate
答案 5 :(得分:0)
这个怎么样?
SELECT
p.user_id,
MAX(p.payment_date) as lastPayment,
CASE COUNT(p.payment_id) WHEN 1 THEN 1 ELSE 0 END as isFirstPayment
FROM
payment p
GROUP BY
p.user_id