tsql将行转换为列而不进行分组

时间:2018-06-14 03:34:44

标签: sql sql-server tsql

这是表格架构,

CREATE TABLE [LOGIN]
(
    [USER_ID] [INT] NOT NULL,
    [ACTION] [VARCHAR](50) NULL,
    [MODIFIED_DATE] [DATETIME] NOT NULL,
    [IS_SUCCESS] [BIT] NOT NULL
) ON [PRIMARY]
GO

这是我的查询结果:

USER_ID    ACTION      MODIFIED_DATE             IS_SUCCESS
-------    ------      -----------------         -----------
0001       Log In      2018-06-01 13:44:02       1
0001       Log Out     2018-05-31 22:56:21       0
0001       Log In      2018-05-31 12:27:40       1
0001       Log Out     2018-05-30 23:43:05       0
0001       Log In      2018-05-30 12:28:08       1
0001       Log In      2018-05-30 12:28:07       1

我想要这样的事情:

USER_ID   Log In                   Log Out
-------   -------------------      -------------------
0001      2018-06-01 13:44:02      NULL
0001      2018-05-31 12:27:40      2018-05-31 22:56:21
0001      2018-05-30 12:28:08      2018-05-30 23:43:05
0001      2018-05-30 12:28:07      NULL

这可能吗?我已经尝试过Stackoverflow的其他帖子,但大多数都在计算或使用组。我不想分组。

2 个答案:

答案 0 :(得分:1)

您可以使用lead()

select l.user_id, l.modified_date as log_in,
       (case when next_a = 'Log out' then next_md end) as log_out
from (select l.*,
             lead(modified_date) over (partition by user_id order by modified_date) as next_md,
             lead(action) over (partition by user_id order by modified_date) as next_a
      from login l
     ) l
where l.action = 'Log in';

这会查看下一条记录,记住它的日期和操作。然后它会过滤到只有登录,并使用逻辑在下一行注销时选择正确的值。

答案 1 :(得分:0)

您可以使用简单的案例陈述来执行此操作。

SELECT  USER_ID , 
(CASE WHEN Action= 'Log In' AND  IS_SUCCESS= 1 then MODIFIED_DATE ELSE  NULL END ) AS 
LOG_IN,
(CASE WHEN Action= 'Log Out' AND  IS_SUCCESS= 1 then MODIFIED_DATE ELSE  NULL END ) AS 
LOG_OUT,  
FROM [LOGIN]