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 |
raindear
Yak Posting Veteran
64 Posts |
Posted - 2014-04-10 : 11:41:14
|
I have two tablesCustomer and AddressBoth have a unique identifier CustomerIDHow can I write a SQL statement that queries the Address table for postcodes of a certain region. The script I have so fair is thisselect c.CustomerID, c.FirstName + ' ' + c.LastName AS CustomerName, c.Email, count(o.OrderNumber) As NoOrdersfrom customer cjoin dbo.Orders_ShoppingCart os with (NOLOCK) on os.CustomerID = c.CustomerIDjoin dbo.Product p with (NOLOCK) on p.ProductID = os.ProductIDjoin dbo.Orders o with (NOLOCK) on o.OrderNumber = os.OrderNumberjoin dbo.Address a with (NOLOCK) on os.CustomerID = a.CustomerIDand c.IsRegistered = 1and p.SKU like '%'and a.Zip Like 'PE30%'or a.Zip Like 'PE31%'or a.Zip Like 'PE32%'or a.Zip Like 'PE33%'or a.Zip Like 'PE34%'or a.Zip Like 'PE35%'GROUP BY c.CustomerID, c.FirstName + ' ' + c.LastName, c.Emailorder by c.CustomerIDBut this pulls in all orders. I just want the customer name, email and those where the zip is beginning ith PE30 etc. |
|
raindear
Yak Posting Veteran
64 Posts |
Posted - 2014-04-10 : 12:00:24
|
Now have this put its pulling in all customers, not just those with a zip beginning with PEselect c.CustomerID, c.FirstName + ' ' + c.LastName AS CustomerName, c.Emailfrom customer cjoin dbo.Address a with (NOLOCK) on c.CustomerID = a.CustomerIDand c.IsRegistered = 1and a.Zip Like 'PE30%'or a.Zip Like 'PE31%'or a.Zip Like 'PE32%'or a.Zip Like 'PE33%'or a.Zip Like 'PE34%'or a.Zip Like 'PE35%'GROUP BY c.CustomerID, c.FirstName + ' ' + c.LastName, c.Emailorder by c.CustomerID |
|
|
Neelmani
Starting Member
2 Posts |
Posted - 2014-04-10 : 12:15:00
|
use join to join tables.Neelmani |
|
|
Neelmani
Starting Member
2 Posts |
Posted - 2014-04-10 : 12:16:58
|
SELECT p.Name, v.NameFROM Production.Product pJOIN Purchasing.ProductVendor pvON p.ProductID = pv.ProductIDJOIN Purchasing.Vendor vON pv.BusinesEntityID = v.BusinessEntityIDWHERE ProductSubcategoryID = 15ORDER BY v.NameNeelmani |
|
|
Ifor
Aged Yak Warrior
700 Posts |
Posted - 2014-04-10 : 12:17:10
|
You probably need brackets around the ORs.Maybe try something like:WITH OrderCountAS( SELECT CustomerID, COUNT(DISTINCT OrderNumber) AS NoOrders FROM dbo.Orders_ShoppingCart GROUP BY CustomerID)SELECT C.CustomerID, C.FirstName + ' ' + C.LastName AS CustomerName, C.Email, O.NoOrdersFROM customer C JOIN OrderCount O ON C.CustomerID = O.CustomerIDWHERE C.IsRegistered = 1 AND EXISTS ( SELECT 1 FROM dbo.[Address] A WHERE A.CustomerID = C.CustomerID AND A.Zip LIKE 'PE3[0-5]%' -- AND (A.Zip LIKE 'PE30%' OR A.Zip LIKE 'PE31%' OR A.Zip LIKE 'PE32%') -- etc ) |
|
|
raindear
Yak Posting Veteran
64 Posts |
Posted - 2014-04-10 : 12:23:12
|
Thanks IFOR! |
|
|
|
|
|
|
|