如何将日期列按天分成多个列?

时间:2019-05-22 20:45:51

标签: sql sql-server tsql sql-server-2008

我有下表显示员工每天在分配的工作中工作的小时数。

   emp_num   |  job   |      initial_date     |  worked_hours
  ----------  --------  ---------------------  -------------
    100001     VESS_10   2019-01-01 06:00:00         2
    100001     VESS_20   2019-01-01 08:00:00         1 
    100001     VESS_30   2019-01-02 06:00:00         1
    100002     VESS_20   2019-01-02 08:00:00         2 
    100002     VESS_20   2019-01-03 10:00:00         2
    100003     VESS_30   2019-01-01 11:00:00         1

我想显示以下结果:

   emp_num   |  job   |      2019-01-01    |    2019-01-02      |    2019-01-03   |  worked_hours
  ----------  --------  -------------------   ---------------   ------------------  ------------
    100001     VESS_10   2019-01-01 06:00:00     NULL                  NULL             2
    100001     VESS_20   2019-01-01 08:00:00     NULL                  NULL             1
    100001     VESS_30          NULL          2019-01-02 06:00:00      NULL             1
    100002     VESS_20          NULL          2019-01-02 08:00:00      NULL             2
    100002     VESS_20          NULL             NULL              2019-01-03 10:00:00  2
    100003     VESS_30   2019-01-01 11:00:00     NULL                  NULL             1

我尝试使用以下查询来旋转表格:

select * from 
    (
     select emp_num, job, initial_date worked_hours
     from transactions
     where initial_date between '2019-04-21 00:00:00' and '2019-04-27 23:59:59'
)
as hours_table
pivot (
    sum(worked_hours)
    for initial_date in (['my problem comes here'])])
)

上面代码的问题是,在for语句中,我想在7列中声明日期,因为它们代表一周中的每一天,但是,我不知道如何基于日期,然后将其分配在正确的列中。

任何帮助,评论或建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个-

SELECT *
FROM
(
    SELECT B.emp_num,B.initial_date,B.Date_Only,B.job,
    (
        SELECT SUM(worked_hours) 
        FROM transactions 
        WHERE emp_num = B.emp_num AND  job = B.job
    ) worked_hours
    FROM 
    (
        SELECT emp_num,job,initial_date,worked_hours,CAST(initial_date AS DATE) Date_Only 
        FROM transactions
    )B
    WHERE initial_date between '2018-12-30 00:00:00' and '2019-01-05 23:59:59'
) A
PIVOT
(
    MAX(initial_date)
    FOR Date_Only IN ([2019-01-01],[2019-01-02],[2019-01-03])
)PVT