SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help with multiple records
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Vicki83
Starting Member

United Kingdom
1 Posts

Posted - 05/30/2012 :  12:09:25  Show Profile  Reply with Quote

Hi, this is the newbies section right? I am still learning SQL code and get a bit stuck with slightly more complicated commands..and at the moment have no available colleagues to help me.

I have a DB that holds numerous items per customer, however I want all the customers that dont have a particular item assigned to them.

For example:
Cust Name/ Item assigned
Joe Bloggs/ Laptop
Joe Bloggs/ Monitor
Joe Bloggs/ Keyboard
Bob Smith/ Laptop
Bob Smith/ Monitor
Bob Smith/ Keyboard
Sam Jones/ Desktop
Sam Jones/ Monitor
Sam Jones/ Keyboard

As you can see from the list above out of 3 ppl they all have an item assigned, but only 2 have laptops - i want to get a list of all that dont have a laptop (e.g. Sam Jones).

Am i missing a simple command that does this?

Thanks

Lamprey
Flowing Fount of Yak Knowledge

3829 Posts

Posted - 05/30/2012 :  12:22:00  Show Profile  Reply with Quote
Here is a break down of one way to get the result you want:
DECLARE @Foo TABLE (CustName VARCHAR(50), ItemAssigned VARCHAR(50))

INSERT @Foo (CustName, ItemAssigned)
VALUES
('Joe Bloggs', 'Laptop'),
('Joe Bloggs', 'Monitor'),
('Joe Bloggs', 'Keyboard'),
('Bob Smith', 'Laptop'),
('Bob Smith', 'Monitor'),
('Bob Smith', 'Keyboard'),
('Sam Jones', 'Desktop'),
('Sam Jones', 'Monitor'),
('Sam Jones', 'Keyboard')

-- Get all DISTINCT Customers
SELECT DISTINCT CustName
FROM @Foo

-- Get all Users with laptops
SELECT CustName
FROM @Foo
WHERE ItemAssigned = 'LapTop'


-- Combine Queries
SELECT *
FROM
	(
		SELECT DISTINCT CustName
		FROM @Foo
	) AS Cust
LEFT OUTER JOIN
	(
		SELECT CustName
		FROM @Foo
		WHERE ItemAssigned = 'LapTop'
	) AS CustWithLaptops
	ON Cust.CustName = CustWithLaptops.CustName
WHERE
	CustWithLaptops.CustName IS NULL
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47099 Posts

Posted - 05/30/2012 :  15:46:33  Show Profile  Reply with Quote

SELECT [Cust Name]
FROM Table
GROUP BY [Cust Name]
HAVING SUM(CASE WHEN [Item assigned]='Laptop' THEN 1 ELSE 0 END) = 0


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000