0

我正在尝试从两个表中进行复杂的查询...这是技能测验中的一个问题。

桌子

**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

它给了我一个错误,说子查询返回超过 1 行

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 `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 回答
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 回答