我已经找到了一些答案,但这里没有任何帮助。我需要一个查询,在一个月内找到每个销售渠道(共5个)的前10个产品。我已经尝试过一个怪异的联盟所有查询,但我没有得到我需要的结果。 (我认为我写的查询并不是最好的,无论如何......)
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
在不查询db 5次的情况下获得结果的最佳方法是什么?
现在我只获得整体最佳产品 - 但不是销售渠道特定的......
答案 0 :(得分:2)
试试这个:
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;
答案 1 :(得分:0)
也许这种查询可能有用:
SELECT
b.SalesChannel, 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
b.SalesChannel, a.SKU, b.SalesChannel
ORDER BY
b.SalesChannel ASC, pq DESC LIMIT 50
我希望它可以以任何方式提供帮助