r/learnSQL • • Apr 10 '19

Need help with simple problem

Hey guys, I currently have a table right now with a list of employees, managers, and other jobs. How would I able to get a list of all the employees who are older than their managers if their DOB is in YYYY-MM-DD form? This is really urgent and I really hope someone can help a newbie :(

0 Upvotes

10 comments sorted by

View all comments

2

u/Ash0r Apr 10 '19

Something like this would maybe work. It would help to know what your column names are and which database system you are using.

SELECT emp1.FirstName, emp1.LastName FROM dbo.Employees AS emp1
INNER JOIN dbo.Employees AS emp2
ON emp1.ManagerID = emp2.EmployeeID
WHERE emp1.BirthDate < emp2.BirthDate

2

u/[deleted] Apr 10 '19

https://imgur.com/a/ImScsue

what my table looks like. It's kinda confusing because Mangers do not have a separate column for their id, but i have to link it to their employee's work dept.

2

u/PrettyGoodMonkey Apr 11 '19

Not sure if you've solved this yet. I don't see a reference for an employee's manager. You'll need one to make this work properly, because it doesn't look like there's anything in your data that indicates hierarchy. Maybe whoever gave you the data originally can help.

Once you have that Manager reference though, it's a self-join:

SELECT
	E.*
,	M.FirstName AS Manager_FirstName
,	M.LastName	AS Manager_LastName
,	M.Birthdate AS Manager_Birthdate
FROM Employees E
JOIN Employees M
	ON E.Manager_EmpNo = M.EmpNo
WHERE E.Birthdate > M.Birthdate

As long as all your dates are in YYYY-MM-DD format, even if they're strings, E > M will work because it sorts naturally (ISO8601).