2013-07-25 2 views
0

레코드 집합이 있고이 레코드를 그룹의 항목 수를 기반으로 정렬하려고합니다.그룹의 항목 수에 따라 레코드 정렬 - SQL Server

The below image is a snapshot of the table

내가 항목의 최대 수와 제품 PRODUCT_ID 3 IS-필요한 순서, 즉 위쪽에있는 같은 방법으로 레코드를 정렬 할 (6 개 항목), 다음 5 (1 PRODUCT_ID 항목)이고 마지막 항목은 Product_ID 2 (3 항목 포함)입니다.

다음 쿼리는 동일한 Product_ID를 가진 항목의 수를 반환하지만 Item_Name, Item_Description 및 Item_Number도 정렬되도록합니다. 다음과 같이

Select Product_ID, Count(*) from Product group by Product_ID order by Count(*) DESC 

나는 다른 쿼리를 시도,하지만 난 내가 잘못 어딘가에는 원하는 결과를 제공하지 않고 내가 가능한 솔루션 생각할 수없는 나는 알고

Select Product_ID, Item_Name, Item_Description, Item_Number from Product 
group by Product_ID,item_name,item_description,item_number 
order by COUNT(product_ID) 

감사에서 당신의 도움을 위해 사전에 !! 당신이 모든 당신이 경우 그룹화 할 필요가 없습니다, 당신은 ID로 그룹화 할 가정

Select Product_ID, Count(*) AS num_products from Product group by Product_ID order by num_products DESC; 

답변

4
Select Product_ID, Item_Name, Item_Description, Item_Number 
from Product 
order by COUNT(1) over (partition by Product_ID) desc 
+0

굉장하고, 매력처럼 작동합니다. 고맙습니다! – pk188

0

별칭을 사용해보십시오 다음으로 주문하고 싶습니다.

SELECT product_id, 
     item_name, 
     item_description, 
     item_number 
FROM product p1 
ORDER BY (SELECT Count(product_id) 
      FROM product p2 
      WHERE p1.product_id = p2.product_id) DESC 
1

하지만 당신은 다른 모든 필드를 나열 할 :

+0

네, 맞습니다. 그룹별로 검색 할 필요가 없으며 쿼리가 정확하게 작동합니다. – pk188

관련 문제