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.
Author |
Topic |
C3000
Starting Member
3 Posts |
Posted - 2007-07-30 : 02:04:26
|
I'm trying to create a query that returns customers who ordered only 1 product, and another for only 2 products. For example if I had 2 tables tblCustomer(ID, Name) and tblOrder(OrderNbr,Product). Any thoughts? |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-07-30 : 02:46:34
|
Yes.1) INNER JOIN2) HAVING3) COUNTBut before all these, how do you know which orders belongs to which customer? E 12°55'05.25"N 56°04'39.16" |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-07-30 : 02:49:12
|
[code]SELECT c.ID, c.NameFROM tblCustomer AS cINNER JOIN tblOrder AS o ON o.CustomerID = c.IDGROUP BY c.ID, c.NameHAVING COUNT(*) = 1 -- 2 if you want customers with exactly 2 ordersORDER BY c.Name, c.ID DESC[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
C3000
Starting Member
3 Posts |
Posted - 2007-07-30 : 23:17:07
|
Thanks that got me on the right track. My next question is if I wanted all customers that only bought 1 type of product. For example, all customers that bought any number of apples, but nothing else. Would that go in the WHERE or HAVING clause? tblC(ID,name) and tblO(OrderNbr,Product,ID)etc. Thanks |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-07-31 : 02:09:34
|
HAVING COUNT(DISTINCT ProductType) = 1 E 12°55'05.25"N 56°04'39.16" |
 |
|
|
|
|