简体   繁体   中英

Count(*) with inner join and group by

I have 2 tables.

I need to get the number of counts with id from table 2 and get the name for the id from table 1.

I tried the following code. Didn't work!

select orders.CustomerID, customers.ContactName , count(*) 
from Orders 
  left join customers on Customers.CustomerID= Orders.customerid 
group by Orders.customerid;

Pls explain my shortcomings if possible.

When grouping the group by section of the query needs to mention all columns tat appear outside of an aggregate like COUNT. You're missing the ContactName here. A fixed version:

select orders.CustomerID, customers.ContactName , count(*) 
from Orders 
left join customers on Customers.CustomerID= Orders.customerid 
group by Orders.customerid, customers.ContactName;

Alternatively you can group by ID alone and then make the join like this:

With OrderCounts AS
(
select orders.CustomerID , count(*)  AS OrderCount
from Orders 
group by Orders.customerid
)
SELECT OrderCounts.CustomerID
, customers.ContactName
, OrderCounts.OrderCount
FROM OrderCounts
left join customers on Customers.CustomerID= OrderCounts.CustomerID 

The first version is shorter and easier to type. In some scenarios the second version will run faster as the group by occurs on a single table & column.

For the second to give the same results CustomerID must be unique in the customers table otherwise it will produce duplicates (but if that's the case the first example would double count orders).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM