목록의 순위를 구해야했는데, JAVA에서 처리하는 법과 Query로 처리하는 법 둘 다 정리해보고자 한다.
중복 순위 개수만큼 다음 순위 값을 증가 시켜라
public class Test {
private static List<Integer> rankOfScore = new ArrayList<>(Arrays.asList(new Integer[101]));
private static List<Integer> input = Arrays.asList(77, 79, 82, 100, 66, 77);
static {
for (int score = 0; score <= 100; score++) {
// 이 점수보다 높은 점수에 몇명이 있는지만 판별
long rank = input.stream()
.filter(s -> s > score)
.count();
rankOfScore.set(score, (int) rank + 1);
}
}
public static String solution(List<Integer> scores) {
List<Integer> result = scores.stream()
.map(score -> rankOfScore.get(score))
.collect(Collectors.toList());
return result.toString();
}
public static void main(String[] args) {
System.out.println(solution(input));
}
}
private List<BrandPrdtSalesDto> setPrdtRanking(List<BrandPrdtSalesDto> targetList) {
// 판매량 작은것부터 정렬
List<Integer> rankOfScore = targetList.stream()
.sorted(Comparator.comparing(BrandPrdtSalesDto::getSalesQy))
.map(i -> i.getSalesQy())
.collect(Collectors.toList());
// (index,saleQy) 형태로 사용
Map<Integer,Integer> scoreMap = IntStream.range(0,rankOfScore.size())
.boxed()
.collect(Collectors.toMap(i -> i,rankOfScore::get));
Map<Integer,Integer> resultMap = new HashMap<>();
// 랭킹구하기
scoreMap.entrySet().stream()
.forEach(index -> {
Integer salesQy = index.getValue();
long rank = targetList.stream()
.filter(s -> s.getSalesQy() > salesQy)
.count();
resultMap.put(salesQy,(int) rank + 1); //(salesQy,ranking)
});
//랭킹 세팅
...
return targetList;
}
select b.BRAND,
b.MONTHLY_SALES_QY,
RANK() over (ORDER BY b.MONTHLY_SALES_QY desc ) as rank_salesQy
from STATS_BRAND_SALE b
where b.KEYWORD_ID = 6 and b.BRAND != ''
group by b.BRAND
order by b.MONTHLY_SALES_QY desc ;
| brand | montly_sales_qy | rank |
|---|---|---|
| 필립스 | 46 | 1 |
| 오랄비 | 46 | 1 |
| 위니아 | 34 | 3 |
| 샤오미 | 31 | 4 |
select b.BRAND,
b.MONTHLY_SALES_QY,
DENSE_RANK() over (ORDER BY b.MONTHLY_SALES_QY desc ) as rank_salesQy
from STATS_BRAND_SALE b
where b.KEYWORD_ID = 6 and b.BRAND != ''
group by b.BRAND
order by b.MONTHLY_SALES_QY desc ;
| brand | montly_sales_qy | rank |
|---|---|---|
| 필립스 | 46 | 1 |
| 오랄비 | 46 | 1 |
| 위니아 | 34 | 2 |
| 샤오미 | 31 | 3 |
참고 블로그