2016-09-03 2 views
0

문제는 내가 대답목록 매년 상위 3 판매 제품

CalendarYear ProductKey EnglishProductSubcategoryName SALES 
2006 312 Road Bikes 658401.68 
2006 313 Road Bikes 608305.90 
2006 310 Road Bikes 608305.90 

select top 3 b.CalendarYear,c.ProductKey, d.EnglishProductSubcategoryName ,SUM(a.SalesAmount) as SALES 
from FactInternetSales as A inner join dimdate as B 
on a.OrderDateKey =b.DateKey 
inner join DimProduct as c 
on c.ProductKey = a.ProductKey 
inner join DimProductSubcategory as d 
on c.ProductSubcategoryKey = d.ProductSubcategoryKey 
inner join DimProductCategory as e 
on d.ProductCategoryKey=e.ProductCategoryKey 
group by b.CalendarYear,c.ProductKey, d.EnglishProductSubcategoryName 
order by SALES desc 

다음있어 다음과 같은 쿼리를 실행

"매년 상위 3 판매 제품 목록"입니다

내 검색어는 "년 2006"데이터가 모든 연도가 아닌 왜 왔는지입니다.

+5

[mySQL] 일 수 없습니다. MySQL은'TOP n' 구문을 사용하지 않습니다. –

+4

바로 태그를 받으셨습니까? 'select top 3'은 mysql 구문이 아닙니다. –

+1

2006 년 도로 자전거가 뜨거웠습니다. – trincot

답변

0

일반적인 생각은 카운터가 작 된 기록 (1 2 3) 행의 각 그룹에 열 카운터를 추가 한 다음 선택하는 3

1

를 사용하여 아래의 쿼리에 동일 수 ...

; WITH cte_1 
    AS 
    (SELECT CalendarYear,ProductKey 
         ,EnglishProductSubcategoryName,SALES 
        ,ROW_NUMBER() OVER(PARTITION BY 
          CalendarYear,ProductKey 
          ,EnglishProductSubcategoryName 
         ORDER BY Sales DESC) RNO 
     FROM (select b.CalendarYear,c.ProductKey 
           ,d.EnglishProductSubcategoryName 
           ,SUM(a.SalesAmount) as SALES 
         from FactInternetSales as A 
          inner join dimdate as B 
           on a.OrderDateKey =b.DateKey 
          inner join DimProduct as c 
           on c.ProductKey = a.ProductKey 
          inner join DimProductSubcategory as d 
           on c.ProductSubcategoryKey = d.ProductSubcategoryKey 
          inner join DimProductCategory as e 
           on d.ProductCategoryKey=e.ProductCategoryKey 
         group by b.CalendarYear,c.ProductKey 
          , d.EnglishProductSubcategoryName)t 
) 
    SELECT CalendarYear,ProductKey 
         ,EnglishProductSubcategoryName,SALES 
    FROM cte_1 
    WHERE RNO<4 
    ORDER BY CalendarYear DESC,RNO ASC 

제공된 스크립트에서 결과 set3에서 top3 레코드 만 선택하면 출력으로 ony 3 레코드가 표시됩니다.

+0

감사합니다. unnikrishnan R 님, 새 학습자입니다.이 답변은 나에게 매우 유용합니다. CTE 기능을 사용해야하는 방법과시기를 알려주십시오. –

+0

간단히 말하면, CTE는 필터 나 기준을 적용 할 수있는 결과 세트를 보유한 임시 테이블의 역할을 할 것이라고 말할 수 있습니다. 즉, 추가 계산을 위해 결과 세트를 사용할 수 있습니다. 그러나 CTE를 재귀 쿼리에 사용할 수도 있습니다 또한이 링크에서 재귀 적 cte에 대해 더 많이 배울 수 있습니다. [link] (https://technet.microsoft.com/en-us/library/ms186243(v=sql.105) .aspx) –

관련 문제