sql - 根据另一列的值条件在 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
任何帮助是极大的赞赏!!
解决方案
您可以使用聚合:
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;
这适用于您的示例数据,因为每个用户最多有两行。如果您的真实数据更复杂,这将只返回每个数据的最大值。
但是,这种情况可能会变得相当复杂。如果这是你真正需要的,你应该问一个新问题。一定要说明当给定类型的交易有多个/丢失时该怎么做——或者清楚地解释为什么这是不可能的。
推荐阅读
- python - 获取历史信息以在 pandas 中创建计算列
- java - 如何在两个 UDP 客户端之间发送消息?
- sql - SQL - 如果存在则匹配值;否则匹配 NULL
- json - Manifest V3 中的远程托管代码替换
- python - Python 正则表达式匹配第一个和最后一个字符
- javascript - Konva hasIntersection js
- mysql - 无法连接到 AWS 上的 MySQL 服务器。AWS 表示拒绝访问客户端并将 AWS 主机名替换为本地 IPv4 地址
- python - 如何根据同一熊猫数据框中列的值复制行
- gatling - scala - Gatling - 我似乎无法在后续请求中使用从请求中存储的会话变量
- nginx - NGINX 无法重写 html