2014-11-19 3 views
0

피벗 테이블을 사용하여 Excel에서이 작업을 수행 할 수 있지만이 작업을 단일 SQL 쿼리에서 직접 수행하는 방법을 알고 싶습니다. 이제 나는 과일의 목록과 신선도 있다고 가정 해 봅시다 :가장 일반적인 두 번째로 가장 일반적인 세 ​​번째로 가장 많이 나타나는 항목을 반환하는 SQL 쿼리

**Fruit Freshness** 
Banana New 
Banana Ripe 
Apple Ripe 
Orange Old 
Cherry New 
Orange Ripe 
Apple Old 
Banana Old 
Apple New 
Apple New 
Orange Ripe 
Banana Old 
Orange New 
Cherry New 
Cherry Ripe 

내가 다음 등 가장 자주 가장 자주 2, 및로 순위를 매기은 "신선도"발생을 계산합니다. 결과는 다음과 같습니다.

**Fruit Most common 2nd most common 3rd most common** 
Banana New   Old    Ripe 
Apple Old   New    Ripe 
Orange Ripe  New    Old 
Cherry New   Ripe   NA 

하나의 쿼리로 가능합니까?

가 같은 값을 반환합니다
SELECT 
    Fruit, GROUP_CONCAT(Freshness ORDER BY cnt DESC) as Common 
FROM (
    SELECT Fruit, Freshness, COUNT(*) cnt 
    FROM 
    fruits 
    GROUP BY 
    Fruit, Freshness 
) s 

: 당신은 세 개의 열에서 결과를 분할하려는 경우

Fruit | Common 
--------------------- 
Banana | New,Old,Ripe 
Cherry | New,Ripe 
... | ... 

는하지만, 이전 쿼리를 결합 할 수 있습니다

+1

편집을보십시오. – Mihai

답변

0

당신은 GROUP_CONCAT() 집계 함수를 사용할 수 있습니다 SUBSTRING_INDEX()을 사용하여 쉼표로 구분 된 값에서 첫 번째, 세 번째 및 세 번째 값을 추출합니다.

SELECT 
    Fruit, 
    SUBSTRING_INDEX(Common, ',', 1) AS most, 
    CASE WHEN CommonLIKE '%,%' 
     THEN SUBSTRING_INDEX(SUBSTRING_INDEX(Common, ',', 2), ',', -1) END AS second_most, 
    CASE WHEN CommonLIKE '%,%,%' 
     THEN SUBSTRING_INDEX(SUBSTRING_INDEX(Common, ',', 3), ',', -1) END AS third_most 
FROM (
    SELECT 
    Fruit, GROUP_CONCAT(Freshness ORDER BY cnt DESC) as Common 
    FROM (
    SELECT Fruit, Freshness, COUNT(*) cnt 
    FROM 
     fruits 
    GROUP BY 
     Fruit, Freshness 
) s 
    GROUP BY 
    Fruit 
) s 
0

SQL Server 2008 및 최대 :

select fruit, [1], [2], [3] from 
(select row_number() over (partition by fruit order by ct desc) as rn, fruit, freshness from (
select count(1) as ct, fruit, freshness from f 
group by fruit, freshness) g) src 
PIVOT 
(
MAX(Freshness) 
FOR rn in ([1], [2], [3]) 
) pvt 
0

는 태그 MySQL과 SQL 서버가 호환되지 않는이

create table #fr (Fruit varchar(20), Freshness varchar(20)) 
insert #fr values 
('Banana' , 'New'),('Banana' , 'Ripe'),('Apple' , 'Ripe'),('Orange' , 'Old'),('Cherry' , 'New'), 
('Orange' , 'Ripe'),('Apple' , 'Old'),('Banana' , 'Old'),('Apple' , 'New'),('Apple' , 'New'), 
('Orange' , 'Ripe'),('Banana', 'Old'),('Orange' , 'New'),('Cherry', 'New'),('Cherry', 'Ripe') 


SELECT Fruit, 
     [1] Most_Common, 
     [2] Second_Common, 
     [3] Third_common 
FROM (SELECT Fruit,Freshness, 
       Row_number()OVER(partition BY Fruit ORDER BY Count(*) DESC) rn 
     FROM #fr 
     GROUP BY Fruit,Freshness) a 
     PIVOT (Max(Freshness) 
      FOR rn IN([1],[2],[3])) piv 
+0

창에서 집계 함수에 의한 주문이 멋지다는 것을 알지 못했습니다. –

+0

@KyleHale - 네, 사용 가능합니다 :) –

관련 문제