sql—来自配置单元格式表的艰巨选择语句

zbwhf8kr  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(317)

请帮我的忙。我在为一个表编写select语句时遇到了问题,希望您能给予帮助。任何sql语法也可以。

对不起,我简化了初始数据。实际数据是一样的。

declare @actions table
(
    actionId varchar(20),
    person int,
    direction bit,
    dt datetime
) 

 insert into @actions values ('1-23', 1, 1, '20180201 09:00:15') insert into @actions values ('1-25', 2, 0, '20180201 09:00:25') insert into @actions values ('21-43', 2, 1, '20180201 09:05:52') insert into @actions values ('2-23', 1, 1, '20180201 09:10:55') insert into @actions values ('16-2', 2, 1, '20180201 09:15:02') insert into @actions values ('11-13', 1, 0, '20180201 09:15:41') insert into @actions values ('2-33', 1, 1, '20180201 09:20:18') insert into @actions values ('7-28', 2, 0, '20180201 09:20:54') insert into @actions values ('1-25', 1, 0, '20180201 09:25:36') insert into @actions values ('10-14', 2, 0, '20180201 09:25:37') insert into @actions values ('10-58', 2, 1, '20180201 09:30:14') insert into @actions values ('31-23', 1, 0, '20180201 09:30:32') insert into @actions values ('11-27', 1, 1, '20180201 09:35:36') insert into @actions values ('5-58', 2, 0, '20180201 09:35:45') insert into @actions values ('8-68', 2, 1, '20180201 09:40:21') insert into @actions values ('8-90', 2, 0, '20180201 09:45:36')

 select * from @actions
r1zk6ea1

r1zk6ea11#

有很多方法可以做到这一点-cte,滞后函数,其他。这可能是最简单的。
我只为第一个用户添加了insert语句。语法是sql server,但应该可以在任何地方使用。
首先,创建和填充数据:

declare @x table(id int, person int, direction int, dt datetime)
insert @x values (1,1,1,'2018-01-02 09:00'),(2,1,1,'2018-02-02 09:12'),(3,1,2,'2018-01-02 09:25')
,(4,1,1,'2018-01-02 09:30'),(5,1,2,'2018-01-02 09:45'),(6,1,2,'2018-01-02 09:50')

现在查询:

select * from (
select x.person, x.id,x.dt,x2.id id2,x2.dt dt2
from @x x
left join @x x2 on x2.id=x.id+1 and x2.person=x.person and x2.direction=2
where x.direction=1
union
select x.person, null,null,x.id,x.dt
from @x x
left join @x x2 on x2.id=x.id-1 and x2.person=x.person 
where x.direction=2 and x2.direction<>1
) q order by isnull(id2,id2)

结果是:

person  id      dt                      id2     dt2
1       1       2018-01-02 09:00:00.000 NULL    NULL
1       2       2018-02-02 09:12:00.000 3       2018-01-02 09:25:00.000
1       4       2018-01-02 09:30:00.000 5       2018-01-02 09:45:00.000
1       NULL    NULL                    6       2018-01-02 09:50:00.000

相关问题