4

我有以下格式的数据

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 
4

2 回答 2

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 
于 2012-08-03T19:53:48.350 回答
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

你可以在这里

于 2012-08-03T20:12:26.957 回答