Friday, June 25, 2010

TOP 10 and Others - SQL

TOP 10 and Others

DECLARE @temp table (SalesAmount FLOAT
, ProductName VARCHAR(100)
, ProductKey INT)
INSERT INTO @temp (SalesAmount
, ProductName
, ProductKey)
SELECT TOP 10 SUM(SalesAmount) AS SalesAmount
,DimProduct.EnglishProductName AS ProductName
,DimProduct.ProductKey AS ProductKey
FROM FactInternetSales
JOIN DimProduct ON DimProduct.ProductKey = FactInternetSales.ProductKey
GROUP BY DimProduct.EnglishProductName
,DimProduct.ProductKey

SELECT CAST(SalesAmount AS NUMERIC(18)) AS SalesAmount
, ProductName
FROM @temp
UNION ALL
SELECT SUM(SalesAmount) AS SalesAmount
, 'Others' AS ProductName
-- , 0 AS ProductKey
FROM FactInternetSales
JOIN DimProduct ON DimProduct.ProductKey = FactInternetSales.ProductKey
WHERE DimProduct.ProductKey
NOT IN (
SELECT ProductKey FROM @temp)