0

2つのテーブルから複雑なクエリを実行しようとしています...スキルクイズからの質問です。

テーブル

**Orders                                    Customer**s
    id                                         id
    date                                     first_name
    shipping_amount                          last_name 
    order_status                             city
    customer_id (Customers.id)             state 

出力

-----------+------------+
| State     |  # Orders  |
+-----------+------------+
| NY        |  55        |
| CA        |  40        |
| NJ        |  33        |
| FL        |  21        |
| MO        |  12        |
+-----------+------------+

私はクエリに取り組んでおり、次のようになります...

select DISTINCT state, (select count(id) Orders
                        from customers
                        group by state
                        ORDER BY Orders DESC) FROM Customers

サブクエリが複数の行を返すというエラーが表示されました

4

4 に答える 4

4

これを試して:

SELECT c.state, COUNT(o.id) AS Orders 
FROM Customers c, Orders o 
WHERE o.customer_id = c.id 
GROUP BY state 
ORDER BY Orders DESC

サブクエリは必要ありません。

于 2010-07-27T04:36:08.693 に答える
0
SELECT c.state as State, COUNT(o.id) as NumOrders
FROM orders o
LEFT JOIN customers c ON (c.id = o.customer_id)
GROUP BY c.state
于 2010-07-27T04:42:50.617 に答える
0
SELECT `Customers`.`state`, count(`Orders`.`id`) 
as `orders FROM `Customers` 
LEFT JOIN `Orders` ON `Customers`.`id` = `Orders`.`customer_id` 
GROUP BY `Customers`.`state` 
ORDER BY `orders` DESC
于 2010-07-27T04:36:40.310 に答える
0

これを試して:

select DISTINCT state, (select count(id) as cnt, Orders from customers group by
    state ORDER BY Orders DESC) Temp FROM Customers
于 2010-07-27T04:39:02.323 に答える