如何使用SQL Server将多行合并为一行

时间:2017-11-09 18:37:21

标签: tsql pivot sql-server-2014

我有一个看起来像这样的桌子

EMP_ID    INpunchDATETIME     OUTpunchDATETIME
-----------------------------------------------
1         2017-11-10 11:59    2017-11-10 13:30
1         2017-11-10 9:00     2017-11-10 10:30

我需要从上一个表中创建一个表@temptable,看起来像这个

Emp_ID InPunch1         InPunch2          OUTpunch1         OUTpunch2 
----------------------------------------------------------------------------
1      2017-11-10 9:00  2017-11-10 11:59  2017-11-10 10:30  2017-11-10 13:30

我正在尝试使用PIVOT但是如果那是错的我可以改变

DECLARE @temptable Table (
        EMP_ID int,
        InPunch1 datetime,
        InPunch2 datetime,
        OutPunch1 datetime,
        OutPunch2 datetime);

SELECT
    Emp_ID, InPunch1, InPunch2, Outpunch1, Outpunch2
INTO
    @temptable
FROM 
    (SELECT
         EMP_ID, INPunchDATETIME, OUTpunchDATETIME
     FROM 
         punches) AS p
PIVOT
    (

这就是我所拥有的。

1 个答案:

答案 0 :(得分:0)

示例数据设置

create table dbo.punches
    (
        emp_id int
        , INpunchDATETIME datetime
        , OUTpunchDATETIME datetime
    )

insert into dbo.punches
values (1, '2017-11-10 11:59','2017-11-10 13:30')
    , (1, '2017-11-10 9:00','2017-11-10 10:30')

<强>答案

打孔表在两个单独的列中具有输入/输出打孔,并且最内部查询将两种类型的打孔移动到一列中以允许所有数据一次pivot。下一个查询按时间顺序排列,并在punch_ind中创建将成为最终列名的值。最后一步是pivot数据并选择最终输出。

select post.emp_id
, post.InPunch1
, post.InPunch2
, post.OutPunch1
, post.OutPunch2
from (
    --decide which punch is in1/in2/etc.
    select sub.emp_id
    , sub.punch_type + 'Punch' + cast(row_number() over (partition by sub.emp_id, sub.punch_type order by sub.punch_ts) as varchar(10)) as punch_ind --punch indicator
    , sub.punch_ts
    from (
        --get all of the data in one column to enable pivot
        select p.emp_id
        , 'In' as punch_type
        , p.INpunchDATETIME as punch_ts
        from dbo.punches as p
        union all
        select p.emp_id
        , 'Out' as punch_type
        , p.OUTpunchDATETIME as punch_ts
        from dbo.punches as p
        ) as sub
    ) as pre --before the pivot
pivot (max(pre.punch_ts) for pre.punch_ind in ([InPunch1], [InPunch2], [OutPunch1], [OutPunch2])) as post --after the pivot

只需将此最终输出和insert记录放入您选择的临时表/表变量中。

相关问题