SQL union all 与 group by
Posted
技术标签:
【中文标题】SQL union all 与 group by【英文标题】:SQL union all with group by 【发布时间】:2020-06-05 16:24:54 【问题描述】:我正在尝试获取员工的休假时间列表,并在网格中显示两年的数据。我已经试过了,没有查询和联合,还有下面的代码,似乎无法让它工作。有什么想法吗?
表格中的数据如下所示:
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
我想要的输出是员工每年在某个 idTask 中的总时间,即假期、工程时间等: 名称 Total2020 Total2019 杰克 48 60
我正在使用 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
【问题讨论】:
用您正在使用的数据库标记您的问题。样本数据和期望的结果会有所帮助。 如果您按 NAME 分组,其他列(如“TotalHours”)必须汇总(例如 SUM() !但是,我不明白您的问题!请您添加一些最少的数据列和您期望的结果? 【参考方案1】:我认为您只需要条件聚合:
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
【讨论】:
我不熟悉sql server中的'and'和'then'语句。当我尝试这个时,他们给出了一个错误 @RayMyers 。 . .您还没有显示这两个表的示例数据(您可以设置一个 DB Fiddle)。但是,and
和 case
是基本 SQL,应该不成问题。以上是关于SQL union all 与 group by的主要内容,如果未能解决你的问题,请参考以下文章