简体   繁体   中英

SQL union all with group by

I am trying to get a list of vacation time for employees and show two years of data in a grid. I've tried this without the just the queries and the union all and also the code below and can't seem to get it to work. Any ideas?

The data in the table looks like this:

ID  IDEmployee IDJob IDTask StartDate Day1 Day2 Day3 Day4 Day5 Day6 Day7  
2472    5   1072    41  2019-01-07  5   4   1   1   2.5 0   0  
2474    5   1072    21  2019-01-07  1   1   2   1.5 1   0   0  
2477    5   1025    21  2019-01-07  2   3   5   2   3   0   0  
2484    9   1049    3   2019-01-07  1   0.5 0   0   0   0   0  
2485    9   1068    41  2019-01-07  6   6.5 7   4.5 8.5 0   0  

The output I would like is a total time for each year that the employee had in a certain idTask which is vacation, engineering time, etc:
Name Total2020 Total2019
Jake 48 60

I'm using sql server

Select Name, TotalHours from (
Select tblEmployee.Firstname + ' ' +  tblEmployee.LastName as Name, sum(day1) + sum(Day2) + sum(day3) + sum(day4) + sum(day5) + sum(day6) + sum(day7) as 'TotalHours' 
from tblTimeSheet 
inner join tblEmployee on tblTimeSheet.IDEmployee = tblEmployee.ID 
where StartDate > '1/1/2020' and idtask in (29,31,32,33) 
group by tblEmployee.Firstname, tblEmployee.Lastname 
--order by Firstname

union all

Select tblEmployee.Firstname + ' ' +  tblEmployee.LastName as Name, sum(day1) + sum(Day2) + sum(day3) + sum(day4) + sum(day5) + sum(day6) + sum(day7) as 'TotalHours' 
from tblTimeSheet 
inner join tblEmployee on tblTimeSheet.IDEmployee = tblEmployee.ID 
where StartDate > '1/1/2019' and StartDate < '1/1/2020' and idtask in (29,31,32,33) 
group by tblEmployee.Firstname, tblEmployee.Lastname 
as x group by Name 

I think you just want conditional aggregation:

Select e.Firstname + ' ' +  e.LastName as Name,
       sum(case when startdate >= '2020-01-01' and 
                then day1 + day2 + day3 + day4 + day5 + day6 + day7
           end) as TotalHours_2020,
       sum(case when startdate >= '2019-01-01' and startdate < '2020-01-01'
                then day1 + day2 + day3 + day4 + day5 + day6 + day7
           end) as TotalHours_2019
from tblTimeSheet ts join
     tblEmployee e
     on t.IDEmployee = e.ID 
where idtask in (29, 31, 32, 33) and
      StartDate >= '2019-01-01'
group by e.Firstname, e.Lastname 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM