我有以下格式的数据
userid amount term APR
1 10 5 1
1 10 4 2
2 20 6 1
2 20 4 3
2 20 3 1
我想按金额,期限,APR做订单,所以在输出中我想要最大金额和相应的期限,APR。如果金额相同,请选择一个最大期限,如果期限也相同则相同。但这三者的结合总是独一无二的。
输出栏:
userid, amount, term, apr, numberOfRowsForEachUser
1 10 5 1 2
2 20 6 1 3
问题:我可以获得前四列,但不知道如何获得“总计不提供优惠”或“每位用户的总行数”。
我的查询看起来像这样。
select
userid,amount,term,apr
from
( select userid, amount, term, apr
RANK() OVER (PARTITION BY userid ORDER BY amount,term,apr) amount_rank,
from
tableXYZ
)
where amount_rank = 1
答案 0 :(得分:5)
只需添加COUNT(*)
分析函数
select
userid,amount,term,apr, cnt
from
( select userid, amount, term, apr
RANK() OVER (PARTITION BY userid ORDER BY amount,term,apr) amount_rank,
COUNT(*) OVER (PARTITION BY userid) cnt
from
tableXYZ
)
where amount_rank = 1
答案 1 :(得分:2)
我喜欢Justing的回答(+1),但仍想提供一个更直观的替代答案:
select x.userid,x.amount,x.term,x.apr,y.cnt
from tableXYZ x, (select userid, COUNT(1) cnt from tableXYZ group by userid) y
where x.term = (select max(term) from tableXYZ xx where xx.userid = x.userid)
and x.userid = y.userid
你可以玩它here