在使用"时的情况下分组"声明

时间:2014-08-22 17:09:50

标签: sql sql-server group-by case-when

我正在尝试在下面的sql语句中按名称分组。可以多次将相同的FirstName输入系统。我希望按行分组以按人(FirstName)计算over_short小时数。

select FirstName,
case 
when managers.title = 'GM' then isnull([TotalSalaryHours],0)-90
when managers.title = '1st' then isnull([RegHours],0)+isnull([OTHours],0)
+isnull([PTO],0)+isnull([HolidayHours],0)-70

End As Over_Short

from Hours
join Managers on managers.Manager_id = hours.manager_id
group by  
FirstName,
case 
when managers.title = 'GM' then isnull([TotalSalaryHours],0)-90
end,
case 
when managers.title = '1st' then isnull([RegHours],0)+isnull([OTHours],0)
+isnull([PTO],0)+isnull([HolidayHours],0)-70
end
, totalsalaryhours, reghours, othours, PTO, holidayhours, totalhourlyhours, title

感谢,

1 个答案:

答案 0 :(得分:0)

只需在像

这样的聚合函数中添加计算
select FirstName,
case 
when managers.title = 'GM' then SUM(isnull([TotalSalaryHours],0))-90
when managers.title = '1st' then SUM(isnull([RegHours],0)+isnull([OTHours],0)
                                +isnull([PTO],0)+isnull([HolidayHours],0))-70

 End As Over_Short
 from Hours
 join Managers on managers.Manager_id = hours.manager_id
 group by  
 FirstName