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
 General SQL Server Forums
 New to SQL Server Programming
 Help with multiple records

Author  Topic 

Vicki83
Starting Member

1 Post

Posted - 2012-05-30 : 12:09:25

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
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-05-30 : 12:22:00
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

52326 Posts

Posted - 2012-05-30 : 15:46:33
[code]
SELECT [Cust Name]
FROM Table
GROUP BY [Cust Name]
HAVING SUM(CASE WHEN [Item assigned]='Laptop' THEN 1 ELSE 0 END) = 0
[/code]

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

Go to Top of Page
   

- Advertisement -