获取每天最受欢迎的产品,MySQL for Magento

时间:2015-07-29 23:44:41

标签: mysql magento

我需要一张包含每天销售最受欢迎产品的表格。所有数据都存储在Magento中,我使用MySQL编写查询。我需要的唯一表是Sales_flat_order_item表。

决赛桌应该有3列:DateProduct SKU,以及当天最受欢迎产品销售的单位数量 - MaxQty

我想出了适合我的查询,但我想知道如何改进它,因为我在代码中使用了两次相同的子查询:

1从Date - 子查询1

中选择Product IdSkuQuantitysales_flat_order_item

2从Date - 子查询2

中选择Maximum QuantitySubquery1

3加入他们,知道日期应该相同,并且Subquery1中的Quantity应该等于Subquery2的最大数量

SELECT DATE( sq2.created_at ) AS CreatedAt, sq0.sku AS SKU, sq2.MaxQty
FROM (

SELECT created_at, product_id, sku, SUM( qty_ordered ) AS qty
FROM  `sales_flat_order_item` 
GROUP BY DATE( created_at ) , product_id
) AS sq0
JOIN (

SELECT sq.created_at, MAX( sq.qty ) AS MaxQty
FROM (

SELECT created_at, product_id, SUM( qty_ordered ) AS qty
FROM  `sales_flat_order_item` 
GROUP BY DATE( created_at ) , product_id
) AS sq
GROUP BY DATE( sq.created_at )
) AS sq2 ON DATE( sq2.created_at ) = DATE( sq0.created_at ) 
AND sq2.MaxQty = sq0.qty
GROUP BY DATE( CreatedAt )

1 个答案:

答案 0 :(得分:0)

我相信这应该做你想要的。 我添加了一个WHERE子句,仅在本月运行它,以防你有一个庞大的数据库,所以它不会花费太多时间。

SELECT day, sku, MAX(qty_total) AS qty FROM (
    SELECT DATE(created_at) AS day, sku, SUM(qty_ordered) AS qty_total
    FROM `sales_flat_order_item` 
    WHERE created_at > '2015-07%'
    GROUP BY sku, day
    ORDER BY qty_total DESC
) AS item_count
GROUP BY day