我还是SQL新手,执行基本功能很有挑战性,所以如果这是一个基本问题我会道歉。
我有几张桌子,其中2张是CUSTOMER和ORDERS。我需要计算每个客户下订单的数量。我正在尝试此代码,但它失败了:
SELECT CUSTOMER.FIRSTNAME || ' ' || CUSTOMER.LASTNAME as CUSTOMER,
COUNT(ORDERS.ORDERID) as ORDERS
FROM customer
INNER JOIN orders
ON customer.CUSTOMERID = orders.CUSTOMERID
GROUP BY CUSTOMER;
有人能告诉我在哪里纠正我的陈述吗?
答案 0 :(得分:3)
您想要的查询如下所示:
SELECT c.FIRSTNAME || ' ' || c.LASTNAME as CUSTOMER, COUNT(o.ORDERID) as NumOrders
FROM CUSTOMER c LEFT JOIN
ORDERS o
ON c.CUSTOMERID = o.CUSTOMERID
GROUP BY c.FIRSTNAME || ' ' || c.LASTNAME;
注意:
GROUP BY
中的列别名。您需要重复表达式(或使用子查询或CTE)。LEFT JOIN
这将包括所有客户,即使是那些没有订单的客户。编辑:
评论中问题的答案:
SELECT c.FIRSTNAME || ' ' || c.LASTNAME as CUSTOMER, COUNT(o.ORDERID) as NumOrders
FROM CUSTOMER c LEFT JOIN
ORDERS o
ON c.CUSTOMERID = o.CUSTOMERID
GROUP BY c.FIRSTNAME, c.LASTNAME
ORDER BY c.LASTNAME;
答案 1 :(得分:0)
这可能更容易理解。结果将略有不同,因为下面将包括没有订单的客户(ORDERS值将为0)。我相信没有性能差异。
select
CUSTOMER.FIRSTNAME || ' ' || CUSTOMER.LASTNAME as CUSTOMER
,(
select COUNT (ORDERS.ORDERID)
from ORDERS
where ORDERS.CUSTOMERID = CUSTOMER.CUSTOMERID
) ORDERS
from
CUSTOMER