Question

I'm currently writing an SQL statement that requires me to list the workers who have a greater hours worked than the average. Here is my current code:

Select T.TotalCandy,Sum(T.Amountofcandy) "Total Candy"
From ToralChocolate 
Inner Join Ompaloompa O 
On T.CandyNo = O.CandyNo and T.BoatNO = O.BoatNo 
Inner Join Transport TR
On TR.Transport = T.Transport 
Having Sum(T.AmountofCandy) > (Select Avg(AmountofCandy) from TotalChocolate)
Group By T.TotalCandy
Order By 1;

I run into my problem at the subquery in the having statement as I'm comparing it to the average hours worked not the average of the SUM of hours worked!

Any help would be appreciated.

Was it helpful?

Solution

Select W.WrkName,Sum(TI.HrsWorked) "Total Hours"
From Timelog TI 
Inner Join Allocation A 
On TI.WrkID = A.WrkID and TI.TaskID = A.TaskID 
Inner Join Worker W 
On TI.WrkID = W.WrkID 
Group By W.WrkName
Having Sum(TI.HrsWorked) > 
    (Select Avg(HrsWorked) 
     From 
        (Select WrkID, SUM(HrsWorked) As HrsWorked 
         From Timelog
         Group By WrkID)
    )
Order By 1;

Have you tried something like that?

OTHER TIPS

Select W.WrkName,Sum(TI.HrsWorked) "Total Hours"
From Timelog TI 
Inner Join Allocation A 
On TI.WrkID = A.WrkID and TI.TaskID = A.TaskID 
Inner Join Worker W 
On TI.WrkID = W.WrkID 
Group By W.WrkName
Having Sum(TI.HrsWorked) > (Select Avg(HrsWorked) from Timelog)
Order By 1;

HAVING CLAUSE AFTER GROUP!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top