I have two tables "contract" and "worker". I need to find the worker which has the most holidays left. However, I only need to print his name, not the holidays.
Contract:
Contract_ID (PK)
Worker_ID (FK)
holidays
Worker
Worker_ID (PK)
Name
contract

worker

Currently I print the information out with this code:
EDIT: The following SQL Code is wrong! It shows Fegelein even though Klink is the person with the most holidays.
SELECT W.Name, MAX(C.Holidays) As Holidays
FROM worker AS W, contract AS C
WHERE W.Worker_ID = C.Worker_ID
Result:
Name Holidays
Fegelein 31
Desired Result:
Name
Fegelein
SQL Fiddle: http://sqlfiddle.com/#!9/a840b/17
So I need to hide the second select MAX(C.Holidays) As Holidays. Is this possible?
Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Or, as a comment I saw yesterday suggests . . . JOIN the modern world.
If you only want one such worker, then use LIMIT:
SELECT w.Name
FROM worker w JOIN
contract c
ON w.Worker_ID = c.Worker_ID
ORDER BY c.Holidays DESC
LIMIT 1;
Most holidays appears to be the smallest value of holiday. If it is the smallest value (as suggested by your question), use ORDER BY c.Holidays ASC.
Presumably, workers might be on multiple contracts, so you might want aggregation. However, that is unclear.
Here is a SQL Fiddle.
Simply try with :
SELECT w.Name
FROM worker w JOIN
contract c
ON w.Worker_ID = c.Worker_ID
ORDER BY c.Holidays DESC
You can add LIMIT 1 if you need only one result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With