按 30 天内的销售额订购产品,其次是没有销售额的产品

Order products by sales within 30 days followed by those without sales

我正在尝试获取过去 30 天内按售出数量订购的产品列表。

我如何进行以下查询,同时按过去 30 天的售出数量排序,然后是在这 30 天内没有售出任何产品的产品?

我首先需要最近 30 天内有销售的产品,然后是之后没有任何销售的产品。

带有销售日期的字段是一个名为 orders.sold_time

datetime 字段

这是我当前的查询:

SELECT    pd.products_id AS id, pd.products_name AS name
FROM      products_description pd
LEFT JOIN products ON pd.products_id = products.products_id
LEFT JOIN orders_products ON pd.products_id = orders_products.products_id
LEFT JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE     pd.c5_dataset = 'DAT'
AND       products.products_status =1
AND       pd.language_id =4
AND       NOT EXISTS (
              SELECT 1
              FROM   products_description
              WHERE  products_id = pd.products_id
              AND    language_id = 10
          )
AND       orders_total.class = 'ot_total'
GROUP BY  pd.products_id
ORDER BY  count( orders_products.products_quantity ) DESC

您可以为此使用 case when 表达式。最近 30 天的销售数量的表达式是:

sum(case when orders.sold_time >= date_add(curdate(), interval -30 day) 
         then orders_products.products_quantity 
    end)

你可以把它放在 order by 子句中,然后你应该决定在过去 30 天内 没有 销售的文章的排序。例如,这可能是历史销量。

我还会为您的所有表格使用别名(就像您为第一个表格所做的那样)。所以 o 代表 ordersop 代表 orders_products

那么你的 order by 看起来像:

order by sum(case when o.sold_time >= date_add(curdate(), interval -30 day) 
                  then op.products_quantity 
             end),
         sum(op.products_quantity)

要检查结果,最好将这两个表达式添加到select列表中。

关于SQL的一些注意事项:

因为您在 products.products_status (=1) 上有一个非空条件,所以没有充分的理由使用 LEFT JOIN products。而是使用更高效的 INNER JOIN.

如果用 INNER JOIN 子句替换 NOT EXISTS 条件,您可能会提高效率:

INNER JOIN products_description p2
       ON p2.products_id = pd.products_id
      AND p2.language_id = 10

前提是每种产品和语言最多只能有一个描述。