1

次の形式で過去 1 年間の注文ごとのユニットの分布を取得する単一の MySQL クエリ (サブクエリは問題ありません) を探しています。

units_per_order | 注文数 | percent_of_total
-------------------------------------------------- -------------------
1 | 7500 | 55%
2
3
4
5
6-10
10-20
30-50
50~100
100+

編集:

照会するテーブルと必要な列:

表: 注文
フィールド: orders_id、date_purchased

表: orders_products
フィールド: orders_id、products_quantity

これは私が今持っているものです:

COUNT(*) AS cnt, qty FROM (
        qty、orders_idとしてSUM(products_quantity)を選択
        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

何か案は?

4

1 に答える 1

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
于 2012-12-04T23:05:55.257 に答える