-2

I need a query that will show only employees who have been paid in more than one state.

The query will pull three columns:

  1. EmployeeID
  2. WorkLocation
  3. LastPayDate

My current, unsuccessful attempt:

Select EmployeeID
    , WorkLocation
    , max(LastPayDate)
from Table 
group by EmployeeID, WorkLocation
having COUNT(distinct WorkLocation) > 1

This query pulls zero records. I know there are employees who have worked in multiple states, however. I am not sure where my logic breaks down.

Any instruction is much appreciated.

2 Answers2

0

You need to have a count(workLocation) > 1 which indicates that they have worked in more than 1 state. Specify this in the HAVING clause. Since you're only concerned in GROUPS which contain multiple WorkLocations.

If you're trying to check for multiple work locations within a specific year, you will perform that logic in the WHERE clause.

select EmployeeId
from table xyz
//where year(LastPayDate) == 2015
group by EmployeeId 
having count(distinct WorkLocation) > 1
JustinDanielson
  • 3,155
  • 1
  • 19
  • 26
0

Figured it out. I needed to use a subquery. Solution as follows:

Select t.EmployeeID
     , t.WorkLocation
     , t.LastPayDate
From Table t
Where t.EmployeeID in
    (
     Select t2.EmployeeID
     From Table t2
     Group by t2.EmployeeID
     Having count(distinct t2.WorkLocation) > 1
    )
Group by t.EmployeeID, t.WorkLocation
Order by t.EmployeeID

Thanks to everyone for helping.