sql - Join two query results where one is created from column values -
i have table tables
table1:
name|starttime|endtime|project_number frank| 12:00| 16:00|project1 frank| 08:00| 16:00|project2 andre| 09:00| 16:00|project4 andre| 11:00| 16:00|project5
i try accomplish table shows time worked , each project this:
table2:
name |all|project1|project2|project3|project4 andre|12 |4 |8 |null |null frank|12 |null |null |7 |5
i can result all
select name, sum(datediff(minute, starttime, endtime)) table1 group name, sum(datediff(minute, starttime, endtime))
and can accomplish table2
(with group on project well) not result want. tried union
maps tables.
anyone can me done?
do datediff
calculation in derived table. (to keep code pretty!)
then use case
expressions conditional aggregation:
select name, sum(ts), sum(case when project_number = 'project1' ts end) project1, sum(case when project_number = 'project2' ts end) project2, sum(case when project_number = 'project3' ts end) project3, sum(case when project_number = 'project4' ts end) project4 ( select name, datediff(minute, starttime, endtime) ts, project_number table1 ) group name
you can skip derived table:
select name, sum(datediff(minute, starttime, endtime)), sum(case when project_number = 'project1' datediff(minute, starttime, endtime) end) project1, sum(case when project_number = 'project2' datediff(minute, starttime, endtime) end) project2, sum(case when project_number = 'project3' datediff(minute, starttime, endtime) end) project3, sum(case when project_number = 'project4' datediff(minute, starttime, endtime) end) project4 table1 group name
Comments
Post a Comment