1

I have the following query

SELECT Dnumber, SUM(WORKS_ON.Hours) AS sum_hours 
FROM DEPARTMENT 
JOIN PROJECT ON DEPARTMENT.Dnumber = PROJECT.Dnum 
JOIN WORKS_ON ON PROJECT.Pnumber = WORKS_ON.Pno 
GROUP BY Dnumber

RESULT:

Dnumber   sum_hours
--------------------
1           25.0
4          115.0
5          150.0

I want to select the row with the MAX sum_hours. I tried using

SELECT s.Dnumber, MAX(s.sum_hours)
FROM 
    (SELECT Dnumber, SUM(WORKS_ON.Hours) sum_hours 
     FROM DEPARTMENT 
     JOIN PROJECT ON DEPARTMENT.Dnumber = PROJECT.Dnum 
     JOIN WORKS_ON ON PROJECT.Pnumber = WORKS_ON.Pno 
     GROUP BY Dnumber) s 
GROUP BY s.Dnumber

But this returns the exact same result (all three rows).

Any idea how I can achieve this?

1 Answer 1

2

try this

SELECT TOP 1 Dnumber, SUM(WORKS_ON.Hours) sum_hours 
FROM DEPARTMENT 
JOIN PROJECT ON DEPARTMENT.Dnumber = PROJECT.Dnum 
JOIN WORKS_ON ON PROJECT.Pnumber = WORKS_ON.Pno GROUP BY Dnumber
ORDER BY SUM(WORKS_ON.Hours) DESC
Sign up to request clarification or add additional context in comments.

1 Comment

what if I wanted to add another column (Pno for example) to the result. Is there a way to achieve that with the same query?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.