Magento:如何查询(SQL)畅销产品?

时间:2016-03-03 10:13:37

标签: sql magento report

我正在寻找一个SQL查询来直接获取我们最畅销产品的清单(按数量或数量排序 - 并不重要)。这似乎比我想象的更难......

使用谷歌搜索只能找到PHP模块的解决方案等等 - 但我想要SQL。

我从其他网站上获取了一个小查询并对其进行了一些修改:

SELECT 
SUM(order_items.qty_ordered) AS ordered_qty, order_items.name AS order_items_name, order_items.product_id AS entity_id, 
e.entity_type_id, e.attribute_set_id, e.type_id, e.sku, e.has_options, e.required_options, e.created_at, 
e.updated_at FROM sales_flat_order_item AS order_items 
INNER JOIN sales_flat_order AS `order` ON `order`.entity_id = order_items.order_id AND `order`.state <> 'canceled' 
LEFT JOIN catalog_product_entity AS e 
ON 
-- (e.type_id NOT IN ('grouped', 'configurable', 'bundle')) 
-- AND 
e.entity_id = order_items.product_id AND e.entity_type_id = 4 
--AND state = "complete"

WHERE (parent_item_id IS NULL) 

GROUP BY order_items.product_id 
HAVING (SUM(order_items.qty_ordered) > 0)

ORDER BY ORDERED_QTY DESC

或多或少似乎给出了合理的输出 - 但数字与admin-start屏幕(仅显示前5位)不同。

有没有人做过什么?类似于那个?

1 个答案:

答案 0 :(得分:1)

现在有一个解决方案(查询)

select
        year_ordered, 
        product_type,
        sku,
        name,
        sum(qty_ordered) as qty,
        sum(row_total) as total
from (

SELECT 
    YEAR(so.created_at) AS year_ordered, 
    -- order_id, 
    product_type, sku, name, qty_ordered, price, row_total


   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

) stat

group by stat.year_ordered, stat.product_type, stat.sku, stat.name
order by year_ordered desc, total desc

我使用子查询来控制计数产品是否正确。

 SELECT 
        YEAR(so.created_at) AS year_ordered, 
        -- order_id, 
        product_type, sku, name, qty_ordered, price, row_total


   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

结果是每年订购产品的列表。如果您想查看所有年份的畅销书列表,只需稍作修改(此处按总数排序)。

select
        product_type,
        sku,
        name,
        sum(qty_ordered) as qty,
        sum(row_total) as total
from (

SELECT 
    YEAR(so.created_at) AS year_ordered, 
    -- order_id, 
    product_type, sku, name, qty_ordered, price, row_total


   FROM `sales_flat_order` AS so
   INNER JOIN `sales_flat_order_item` AS si ON si.order_id=so.entity_id
        AND (so.state != "canceled" )
 ORDER BY so.created_at desc

) stat

group by stat.product_type, stat.sku, stat.name
order by total desc