smhorton
asked on
SQL Query select where field1 = x and field1 = y
I need to be able to select EmployeeID, Employee Name from a table where the same field will have a description Sales or Sales Stocker. The employee has two entries. If I use an and i don't get anything returned if I use or i get everything. I just need the employees that have both.
Can you post the query you are attempting to run?
Try this...
SELECT DISTINCT EmployeeID, Employee_Name from TableName
WHERE Description = 'Sales Stocker' AND Employee_Name IN(Select Employee_Name From TableName WHERE Description = 'Sales')
SELECT DISTINCT EmployeeID, Employee_Name from TableName
WHERE Description = 'Sales Stocker' AND Employee_Name IN(Select Employee_Name From TableName WHERE Description = 'Sales')
SELECT
EmployeeID, Employee_Name
FROM dbo.tablename
GROUP BY EmployeeID, Employee_Name
HAVING
MAX(CASE WHEN Description = 'Sales' THEN 1 ELSE 0 END) = 1 AND
MAX(CASE WHEN Description = 'Sales Stocker' THEN 1 ELSE 0 END) = 1
ORDER BY
EmployeeID, Employee_Name
EmployeeID, Employee_Name
FROM dbo.tablename
GROUP BY EmployeeID, Employee_Name
HAVING
MAX(CASE WHEN Description = 'Sales' THEN 1 ELSE 0 END) = 1 AND
MAX(CASE WHEN Description = 'Sales Stocker' THEN 1 ELSE 0 END) = 1
ORDER BY
EmployeeID, Employee_Name
ASKER
I will post the exact query I am using but it will have to be this afternoon. Sorry. I don't have access to that machine from where I am at. Will also try both of the examples above then as well. Thanks!
ASKER
SELECT [employee_id]
,[first_name]
,[last_name]
,[dept_no]
,[salary]
FROM [AdventureWorks2008].[dbo] .[employee ]
where dept_no = '10' and dept_no ='20'
Above is an example I have made up using adventureworks 2008. the and between the dept_no returns nothing but I have employees setup with both a 10 and a 20 dept number.
,[first_name]
,[last_name]
,[dept_no]
,[salary]
FROM [AdventureWorks2008].[dbo]
where dept_no = '10' and dept_no ='20'
Above is an example I have made up using adventureworks 2008. the and between the dept_no returns nothing but I have employees setup with both a 10 and a 20 dept number.
SELECT [employee_id]
,[first_name]
,[last_name]
,[dept_no]
,[salary]
,COUNT(*)
FROM [AdventureWorks2008].[dbo] .[employee ]
WHERE dept_no IN ('10','20')
GROUP BY [employee_id],[first_name] ,[last_nam e],[dept_n o],[salary ]
HAVING COUNT(*) = 2;
,[first_name]
,[last_name]
,[dept_no]
,[salary]
,COUNT(*)
FROM [AdventureWorks2008].[dbo]
WHERE dept_no IN ('10','20')
GROUP BY [employee_id],[first_name]
HAVING COUNT(*) = 2;
ASKER
The last example just above using adventureworks 2008 doesn't return any rows for me. Sorry.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If dept_no is a numeric datatype, adventureworks might not like doing an implicit conversion. Try removing the quotes -
where dept_no in (10,20)
where dept_no in (10,20)