如何计算sql中的项目数

时间:2014-12-17 09:01:38

标签: mysql sql count

我有这样的表:

CREATE TABLE customers (
    customer_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(100) );

CREATE TABLE orders (
    order_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT,
    amount DOUBLE,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

我需要为每个客户选择订单数量

我试过了:

SELECT orders, COUNT(*)
FROM orders
ORDER BY COUNT(*) DESC

但它没有工作

2 个答案:

答案 0 :(得分:1)

你可以这样做

select
c.customer_id,
count(o.customer_id) as total
from customers c
join orders o on o.customer_id = c.customer_id
group by c.customer_id
order by total desc

以上查询仅针对在orders表中包含数据的客户返回计数,如果您需要计算所有客户,无论orders表中是否有数据,您都需要left join

select
c.customer_id,
coalesce(count(o.customer_id),0) as total
from customers c
left join orders o on o.customer_id = c.customer_id
group by c.customer_id
order by total desc

答案 1 :(得分:0)

您也可以编写以下查询

`SELECT 
    c.customer_id, COUNT(o.order_id)
FROM
    customers c,
    orders o
WHERE
    c.customer_id = o.customer_id
GROUP BY c.customer_id;`