加入两个查询结果,其中一个是从列值

时间:2016-07-04 13:08:38

标签: sql tsql

我有一张桌子

表1:

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

我尝试完成一个表格,显示所有工作时间和每个项目的工作时间如下:

表2:

Name |All|Project1|Project2|Project3|Project4
Andre|12 |4       |8       |Null    |Null
Frank|12 |Null    |Null    |7       |5

我可以获得所有

的结果
Select Name, sum(datediff(Minute, Starttime, Endtime)) from Table1
group by Name, sum(datediff(Minute, Starttime, Endtime))

我也可以为Table2实现这一点(同时也有一个关于Project的组)但我只是没有得到我想要的结果。我已经尝试了UNION,但这只是映射表格。

任何可以帮助我完成任务的人都会这样做吗?

2 个答案:

答案 0 :(得分:2)

在派生表中执行datediff计算。 (为了保持代码漂亮!)

然后使用case表达式进行条件聚合:

select Name,
       sum(ts),
       sum(case when Project_Number = 'Project1' then ts end) as Project1,
       sum(case when Project_Number = 'Project2' then ts end) as Project2,
       sum(case when Project_Number = 'Project3' then ts end) as Project3,
       sum(case when Project_Number = 'Project4' then ts end) as Project4
from
(
    select Name, datediff(Minute, Starttime, Endtime) as ts, Project_Number
    from Table1
)
group by Name

您也可以跳过派生表:

select Name,
       sum(datediff(Minute, Starttime, Endtime)),
       sum(case when Project_Number = 'Project1' then datediff(Minute, Starttime, Endtime) end) as Project1,
       sum(case when Project_Number = 'Project2' then datediff(Minute, Starttime, Endtime) end) as Project2,
       sum(case when Project_Number = 'Project3' then datediff(Minute, Starttime, Endtime) end) as Project3,
       sum(case when Project_Number = 'Project4' then datediff(Minute, Starttime, Endtime) end) as Project4
from Table1
group by Name

答案 1 :(得分:0)

使用CTE

;with
t1 as (  -- your data table
    select * 
    from (
        values
        ('frank', cast('12:00' as time), cast('16:00' as time), 'Proj1'),
        ('frank', cast('08:00' as time), cast('16:00' as time), 'Proj2'),
        ('andre', cast('09:00' as time), cast('16:00' as time), 'Proj3'),
        ('andre', cast('11:00' as time), cast('16:00' as time), 'Proj4')
    ) x (name,startt,endt, prjn) 
),
t2 as (  -- precalc hours per project
    select name, prjn, datediff(hour, startt, endt) difft
    from t1 
),
t3 as (  -- precalc hours per name
    select name, SUM(difft) allt
    from t2
    group by name
),
t4 as (  -- table to pivot
    select t2.*, t3.allt
    from t2
    inner join t3 on t2.name = t3.name  
)
select *
from t4
pivot (sum(difft) for prjn in (Proj1, Proj2, Proj3, Proj4)) p
order by name

tadaaa