将2个日期行合并为1行中的2列

时间:2017-03-05 11:44:45

标签: sql sql-server tsql

我有1个时间记录表,类型1和2.我希望它们合并为1行。

我期待log_type 1没有log_type 2合作伙伴。预期结果将是:

A | 2017-02-01 08:00:00.000 | 2017-02-01 08:10:00.000
A | 2017-02-01 08:30:00.000 |
A | 2017-02-01 08:40:00.000 | 2017-02-01 08:50:00.000
A | 2017-02-01 09:00:00.000 |

这是我的剧本:

create table test_time
(
    person varchar(30)
    ,log_time datetime
    ,log_type int
)

insert into test_time
values
('A','2017-02-01 8:00:00',1)
,('A','2017-02-01 8:10:00',2)
,('A','2017-02-01 8:30:00',1)
,('A','2017-02-01 8:40:00',1)
,('A','2017-02-01 8:50:00',2)
,('A','2017-02-01 9:00:00',1)

另外,我应该能够处理其他人。我已经尝试了ROW_NUMBER但是我被卡住了。提前谢谢。

3 个答案:

答案 0 :(得分:3)

我会尝试以下查询(未经测试):

SELECT y.*
FROM (
    SELECT t.person, t.log_time, t.log_type, 
        ROW_NUMBER() OVER(PARTITION BY t.person ORDER BY t.log_time) - t.log_type AS group_num
    FROM dbo.MyTable AS t
) x
PIVOT( MAX(x.log_time) FOR x.log_type IN ([1], [2])) y
ORDER BY y.person, y.group_num

答案 1 :(得分:1)

我不会将结果放在一个列中。我只想用适当的值定义第二列。

您似乎想要lead()

select t.*,
       (case when next_log_status = 2 then next_log_time end) as log_time_2
from (select t.*, 
             lead(log_time) over (partition by person order by log_time) as next_log_time,
             lead(log_status) over (partition by person order by log_time) as next_log_status
      from test_time t
     ) t
where log_status = 1;

如果您真的希望在一列中包含两个日期,则可以将它们连接在一起。这似乎对我没用。

答案 2 :(得分:0)

使用子查询:

select 
    t1.person,
    t1.log_time,
    (
         select top 1 test_time
         from test_time t2 
         where t1.person = t2.person 
             and t2.log_type = 2
             and t1.test_time <= t2.test_time
         order by test_time asc) log_time2
from test_time t1
where t1.log_type = 1