一直在搞乱Volusion商店的这个问题,试图通过品牌获得最畅销的sku ......而且我已经这样做了,但我怎么能只展示前十大PER品牌....
如果我在前10行添加前10行。
select
products_joined.ProductManufacturer as brand,
Sum(OrderDetails.ProductPrice * OrderDetails.Quantity) AS TotalSold,
OrderDetails.ProductCode as sku
from
orderdetails, orders, products_joined
where
products_joined.ProductCode = OrderDetails.ProductCode
and Orders.OrderID = OrderDetails.OrderID
and Orders.OrderDate BETWEEN getdate() - 90 AND getdate()
and Orders.OrderStatus <> 'Cancelled'
and products_joined.ProductManufacturer is not null
group by
products_joined.ProductManufacturer, OrderDetails.ProductCode
order by
products_joined.ProductManufacturer,
Sum(OrderDetails.ProductPrice*OrderDetails.Quantity) DESC
答案 0 :(得分:1)
如果ROW_NUMBER可用,您也可以使用CTE并执行类似的操作。
;WITH cteProductsSold AS (
SELECT pj.ProductManufacturer AS brand,
od.ProductCode AS sku,
SUM(od.ProductPrice * od.Quantity) AS TotalSold
FROM orders o
INNER JOIN orderdetails od ON od.OrderID = o.OrderID
INNER JOIN products_joined pj ON pj.ProductCode = od.ProductCode
WHERE o.OrderDate BETWEEN GETDATE() - 90 AND GETDATE()
AND o.OrderStatus <> 'Cancelled'
AND pj.ProductManufacturer IS NOT NULL
GROUP BY pj.ProductManufacturer,
od.ProductCode
), cteProductOrdered AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY brand ORDER BY TotalSold DESC) Rn
FROM cteProductsSold
)
SELECT brand,
sku,
TotalSold
FROM cteProductOrdered
WHERE Rn < 11
或者,您可以使用派生表而不是CTE。
SELECT brand,
sku,
TotalSold
FROM ( SELECT *,
ROW_NUMBER() OVER (PARTITION BY brand ORDER BY TotalSold DESC) Rn
FROM ( SELECT pj.ProductManufacturer AS brand,
od.ProductCode AS sku,
SUM(od.ProductPrice * od.Quantity) AS TotalSold
FROM orders o
INNER JOIN orderdetails od ON od.OrderID = o.OrderID
INNER JOIN products_joined pj ON pj.ProductCode = od.ProductCode
WHERE o.OrderDate BETWEEN GETDATE() - 90 AND GETDATE()
AND o.OrderStatus <> 'Cancelled'
AND pj.ProductManufacturer IS NOT NULL
GROUP BY pj.ProductManufacturer,
od.ProductCode
) p
) ps
WHERE Rn < 11
答案 1 :(得分:1)
这也应该有用
select * from (
select
products_joined.ProductManufacturer as brand,
Sum(OrderDetails.ProductPrice*OrderDetails.Quantity) AS TotalSold,
OrderDetails.ProductCode as sku,
row_number() over ( partition by products_joined.ProductManufacturer, OrderDetails.ProductCode order by Sum(OrderDetails.ProductPrice*OrderDetails.Quantity) desc) rowid
from orderdetails, orders, products_joined
where
products_joined.ProductCode = OrderDetails.ProductCode and
Orders.OrderID = OrderDetails.OrderID and
Orders.OrderDate BETWEEN getdate() - 90 AND getdate()
AND Orders.OrderStatus <> 'Cancelled' and products_joined.ProductManufacturer is not null
GROUP BY products_joined.ProductManufacturer, OrderDetails.ProductCode
) as x
where rowid < 11
ORDER BY brand,TotalSold DESC