programing

각 TILL의 최대값과 해당 TILL의 항목 수를 사용하여 결과 집합을 만드는 방법

lovejava 2023. 7. 23. 13:54

각 TILL의 최대값과 해당 TILL의 항목 수를 사용하여 결과 집합을 만드는 방법

이런 자리가 있으면요.

id product_name  price

1   product_1     5    
2   product_2     10 
3   product_3     100
4   product_4     200   
5   product_5     9000     

다음과 같은 쿼리를 실행하는 경우:

 select  price,  ntile(3) over(order by price) as rank from products order by price.

대략적으로 다음과 같은 결과가 생성됩니다.

   id  product_name   price       rank

    1   product_1     5             1
    2   product_2     10            1
    3   product_3     100           2
    4   product_4     200           2
    5   product_5     9000          3

하지만 저는 이것을 조금 더 확장해서 각 타일의 최대값과 타일의 개수를 얻고 싶습니다.

   price    items
    10       2
    200      2
    9000     1  // I think I won't use the last tile max value, but it's here anyway.

저는 제가 원하는 결과를 얻을 수 있는 지식이 없기 때문에 약간의 도움은 환영합니다.

그냥 집계를 이용하면 어떨까요?

select max(price), count(*)
from (select price,  ntile(3) over (order by price) as rank
      from products
     ) p
group by rank
order by price

주의사항일 뿐입니다.ntile()경계 값을 여러 개의 빈으로 분할할 수 있도록 동일한 크기의 빈을 만듭니다.

언급URL : https://stackoverflow.com/questions/55735044/how-to-create-a-result-set-with-the-max-value-of-each-tile-and-the-number-of-ite