【发布时间】:2020-08-16 06:38:54
【问题描述】:
我正在使用 SQL Server。这是场景:
假设我有一个 tableA:
UserId UserName TransactionType TransactionDateTime
1 Staff1 NULL NULL
2 Staff2 1 2020-08-12 03:11:20.4871383
2 Staff2 2 2020-08-12 03:41:33.4850314
3 Staff3 2 2020-08-12 03:41:33.4848626
3 Staff3 1 2020-08-12 03:11:20.4869688
我想查询如下结果:
UserId UserName ClockInTime ClockOutTime
1 Staff1 NULL NULL
2 Staff2 2020-08-12 03:11:20.4871383 2020-08-12 03:41:33.4850314
3 Staff3 2020-08-12 03:11:20.4869688 2020-08-12 03:41:33.4848626
所以条件是type为1则transactiondatetime为clockintime,type为2则为clockouttime。
我尝试使用“case when”:
Select UserId, UserName,
case when TransactionType = 1 Then TransactionDateTime else null End as ClockInTime,
case when TransactionType = 2 Then TransactionDateTime else null End as ClockOutTime
From tableA
这样会返回 5 行:
UserId UserName ClockInTime ClockOutTime
1 Staff1 NULL NULL
2 Staff2 2020-08-16 03:11:20.4871383 NULL
2 Staff2 NULL 2020-08-16 03:41:33.4850314
3 Staff3 NULL 2020-08-16 03:41:33.4848626
3 Staff3 2020-08-16 03:11:20.4869688 NULL
非常感谢任何帮助!
【问题讨论】:
-
请告诉我们你尝试了什么。
标签: sql sql-server datetime datetime2