首页 > 解决方案 > 根据另一列的值条件在 SQL 中添加/选择多个列

问题描述

我正在使用 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

任何帮助是极大的赞赏!!

标签: sqlsql-serverdatetimedatetime2

解决方案


您可以使用聚合:

select UserId, UserName, 
       max(case when TransactionType = 1 Then TransactionDateTime End) as ClockInTime,
       max(case when TransactionType = 2 Then TransactionDateTime End) as ClockOutTime
from tableA
group by UserId, UserName;

这适用于您的示例数据,因为每个用户最多有两行。如果您的真实数据更复杂,这将只返回每个数据的最大值。

但是,这种情况可能会变得相当复杂。如果这是你真正需要的,你应该问一个新问题。一定要说明当给定类型的交易有多个/丢失时该怎么做——或者清楚地解释为什么这是不可能的。


推荐阅读