gpt4 book ai didi

mysql - 尝试获得每个销售 channel 的 TOP 10 产品

转载 作者:行者123 更新时间:2023-11-29 02:23:19 26 4
gpt4 key购买 nike

我已经找到了一些答案,但没有任何帮助。我需要一个查询来查找一个月内每个销售 channel (总共 5 个)的前 10 个产品。我已经通过一个可怕的 union all 查询尝试了我的运气,但我没有得到我需要的结果。 (我认为我写的查询不是最好的,无论如何......)

SELECT a.SKU, a.ProductName, b.SalesChannel, sum(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel = 1 AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU, b.SalesChannel
UNION ALL
SELECT a.SKU, a.ProductName, b.SalesChannel, sum(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel = 2 AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU, b.SalesChannel
UNION ALL
SELECT a.SKU, a.ProductName, b.SalesChannel, sum(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel = 3 AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU, b.SalesChannel
UNION ALL
SELECT a.SKU, a.ProductName, b.SalesChannel, sum(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel = 4 AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU, b.SalesChannel
UNION ALL
SELECT a.SKU, a.ProductName, b.SalesChannel, sum(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel = 5 AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU , b.SalesChannel
ORDER BY pq DESC LIMIT 10

在不查询数据库 5 次的情况下获得结果的最佳方法是什么?

现在我只获得总体上最好的产品 - 但不是特定销售 channel ...

最佳答案

试试这个:

SELECT A.SKU, A.ProductName, A.SalesChannel, A.pq
FROM (SELECT A.SKU, A.ProductName, A.SalesChannel, A.pq,
IF(@SalesChannel = @SalesChannel:=A.SalesChannel, @RowId:=@RowId + 1, @RowId:=1) AS RowNum
FROM (SELECT a.SKU, a.ProductName, b.SalesChannel, SUM(a.PurchasedQuantity) as pq
FROM all_all_orders_items a
INNER JOIN all_all_orders b ON b.AmazonOrderID = a.AmazonOrderID
WHERE b.SalesChannel IN (1, 2, 3, 4, 5) AND b.PurchaseDate BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY a.SKU, b.SalesChannel
ORDER BY b.SalesChannel, pq DESC
) AS A, (SELECT @SalesChannel:=0, @RowId:=1) AS B
ORDER BY A.SalesChannel, A.pq DESC
) AS A
WHERE A.RowNum <= 10
ORDER BY A.SalesChannel, A.RowNum;

关于mysql - 尝试获得每个销售 channel 的 TOP 10 产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27701370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com