SQL Pivot&联盟在普遍存在的问题

时间:2014-12-09 17:22:29

标签: sql pivot union pervasive

我对sql缺乏经验,但我知道我需要一个pivot& amp;在我的桌子上联合以获得我可以使用的结果集。任何帮助都表示赞赏,但我想要实现的是任何一个月,列出每位员工每周工作的时间。

实际表格:

Employee         Date          Hours_Worked

John             141201        10
John             141210        15
John             141220        20
Jane             141203        25
Jane             141206        10

所需表:

Employee          Wk1          Wk2          Wk3          Wk4          Wk5

John              10           15           20           0            0
Jane              35           0            0            0            0

可能值得注意; date列是char(6)数据类型。

我现在一直在做的是有多个查询,每周一次,如下所示:

SELECT employee, sum(hours_worked) as wk1 FROM job_detail WHERE date_sequence BETWEEN '141200' AND '141208' GROUP BY employee;  

但这只是我的一部分,因为我每个人都有一排,即使他们有相同的员工,这是我考虑工会的地方,但理想情况下,结果需要在每个员工一行的列,这是我想到的枢轴。

1 个答案:

答案 0 :(得分:0)

这就是我想出的。可能需要调整日期编号。我确信可能有日期/星期功能,只是不熟悉普及。

select 
    employee,

    SUM(case when RIGHT(date,2) between 0 and 7 then hours_worked else 0 end) as wk1,
    SUM(case when RIGHT(date,2) between 8 and 15 then hours_worked else 0 end) as wk2,
    SUM(case when RIGHT(date,2) between 16 and 21 then hours_worked else 0 end) as wk3,
    SUM(case when RIGHT(date,2) between 22 and 29 then hours_worked else 0 end) as wk4,
    SUM(case when RIGHT(date,2) between 30 and 31 then hours_worked else 0 end) as wk5
from #t
group by employee

输出:

employee             wk1         wk2         wk3         wk4         wk5
-------------------- ----------- ----------- ----------- ----------- -----------
Jane                 35          0           0           0           0
John                 10          15          20          0           0