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

Sql 将2个日期行合并为1行中的2列,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个带有时间记录的表,输入1和2。我想把它们合并成一行 我希望日志类型1没有日志类型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 te

我有一个带有时间记录的表,输入1和2。我想把它们合并成一行

我希望日志类型1没有日志类型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)

此外,我应该能够处理其他人。我已经试过排号了,但我卡住了。提前谢谢。

我不会把结果放在一列中。我只需要用适当的值定义第二列

您似乎想要潜在客户:


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

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

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
使用子查询:

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

第2行第2列应为空。您的查询使用了第三行值
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