Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 INNER JOIN

Author  Topic 

lakers34kb
Starting Member

15 Posts

Posted - 2010-01-29 : 23:36:38
I have 2 different tables: Customers and Orders

I need to:
List all Customers (include CustomerId and CompanyName) that have placed less than 3 orders. Include those who have zero orders placed. Name the count field "OrderCount". Sort by least number of orders placed.

This is what I have so far, but all I have showing is the CustomerID and the count for it. I'm assuming I need to use inner join and that's where I need help, I included a print screen of both the tables.

SELECT CustomerID, count(*)as OrderCount
FROM Orders
GROUP BY CustomerID ORDER BY OrderCount


http://i45.tinypic.com/2lnjzn8.jpg
http://i48.tinypic.com/m936yx.jpg
http://i47.tinypic.com/2lucaq0.jpg

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-01-29 : 23:46:33
[code]
select c.CustomerId, count(o.CustomerId)
from Customers c
left join Orders o on c.CustomerId = o.CustomerId
group by c.CustomerId
having count(c.CustomerId) < 3
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

lakers34kb
Starting Member

15 Posts

Posted - 2010-01-30 : 00:00:24
thank you khtan for the help
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-01-30 : 03:17:14
I think you just want a JOIN (i.e. an inner join) and not a LEFT JOIN.

You will get customers that have no orders, also you will get SQL warning that COUNT() includes NULLs (that's not a big issue, but it can derail!! some applications)
Go to Top of Page
   

- Advertisement -