MySQL在给定年份中分配单位/订单

时间:2012-12-04 21:41:15

标签: mysql

我正在寻找单个MySQL查询(子查询很好),它将按以下格式获得过去一年中每个订单的单位分布:

units_per_order     |     number_of_orders     |     percent_of_total
---------------------------------------------------------------------
1                   |                 7500     |                  55%
2 
3 
4
5
6-10
10-20
30-50
50–100
100+

修改

要查询的表和必要列:

Table: orders
Fields: orders_id, date_purchased

Table: orders_products
Fields: orders_id, products_quantity

这就是我现在所拥有的:

SELECT COUNT(*) AS cnt, qty FROM (
        SELECT SUM(products_quantity) as qty, orders_id
        FROM orders_products op LEFT JOIN orders o USING (orders_id)
        WHERE date_purchased LIKE '2012%'
        GROUP BY orders_id
    ) AS new_table WHERE qty != 0 GROUP BY qty ORDER BY qty

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好的,这就是我最终的结果。请告知您是否有任何方法可以提高效率。

SELECT qty, cnt, ROUND(((cnt / total) * 100)) AS percent FROM (
    SELECT qty, COUNT(*) AS cnt, total
    FROM (
        SELECT
            (
                CASE WHEN (SUM(products_quantity) < 6) THEN SUM(products_quantity)
                    WHEN (SUM(products_quantity) BETWEEN 6 AND 10) THEN 6
                    WHEN (SUM(products_quantity) BETWEEN 11 AND 20) THEN 11
                    WHEN (SUM(products_quantity) BETWEEN 21 AND 50) THEN 21
                    WHEN (SUM(products_quantity) BETWEEN 51 AND 100) THEN 51
                    ELSE 101
                END
            ) AS qty,
            orders_id,
            (
                SELECT COUNT(DISTINCT(orders_id))
                FROM orders JOIN orders_products USING (orders_id)
                WHERE date_purchased LIKE '2012%' AND products_quantity != 0
            ) AS total
        FROM orders_products op JOIN orders o USING (orders_id)
        WHERE date_purchased LIKE '2012%'
        GROUP BY orders_id
    ) AS new_table
    WHERE qty != 0 GROUP BY qty
) AS newer_table