我是寫這樣,寫著邏輯就亂,能否指教一下
select worknumber,sum(workhour) from hourpay group by worknumber
having
sum(workhour) < (select worknumber,round(avg(sumhour),1) as avhour from (select worknumber,sum(workhour) as sumhour from hourpay group by worknumber ) as temptable)
因為每個人加總出的時數 要再加總平均 要和 個人加總平均時數 做比較
簡單弄了個測試, 不知道是不是你想要的(select 有些多餘的欄位, 請自行刪除 ^^)
create table #Work (
workNo varchar(4),
workHour int);
insert into #Work (workNo, workHour)
values ('E001', 9),('E001', 1), ('E002', 19), ('E002', 1),
('E003',29),('E003', 1), ('E004', 39), ('E004', 1);
with List as (
select workNo, Sum(workHour) as WorkHour, avg(workHour) as AvgHour
from #work
group by workNo),
Total as (select Sum(workHour) as TotalWorkHour, avg(workHour) as TotalAvgHour
from #Work)
select *
from List
cross join Total
where List.AvgHour < Total.TotalAvgHour
drop table #Work;
執行結果