sql - 有条件地选择多行并将其插入 SQL Server 中的单行
问题描述
我正在寻找有人指出正确的方向如何在不使用光标的情况下遍历结果集并插入表中。甚至不知道如何问这个。
选择查询的结果集:
------------------------------------------------------
ID | Name | CreatedBy | CreatedDate
------------------------------------------------------
1 A John 2018-04-30
1 B Sam 2018-04-20
2 A John 2018-04-18
-------------------------------------------------------
插入表:
---------------------------------------------------------------------------------------------------------
ID | A_CreatedBy | A_CreatedDate | B_CreatedBy | B_CreatedDate | C_CreatedBy | C_CreatedDate
---------------------------------------------------------------------------------------------------------
1 John 2018-04-30 Sam 2018-04-20 NULL NULL
2 John 2018-04-18 NULL NULL NULL NULL
---------------------------------------------------------------------------------------------------------
任何帮助,将不胜感激。
解决方案
您可以按如下方式使用条件聚合:
select ID,
max(case when name = 'A' then createdby end) as a_createdby,
max(case when name = 'A' then CreatedDate end) as a_CreatedDate,
max(case when name = 'B' then createdby end) as b_createdby,
max(case when name = 'B' then CreatedDate end) as b_CreatedDate,
max(case when name = 'C' then createdby end) as c_createdby,
max(case when name = 'C' then CreatedDate end) as c_CreatedDate
from (your_query) t
group by ID
推荐阅读
- c# - 如何在 C# 中将对象序列化/反序列化为 avro
- angular - Jasmine 测试错误:预期的间谍已被调用
- php - Laravel 和 PHP:没有技巧就无法访问数组项,这是为什么呢?
- lingo - 派生变量停留在 0(无法求解固定变量)
- amazon-s3 - 从一个 AWS 子账户流式传输 S3 文件,Flink 部署在另一个 AWS 账户的 Kubernetes 集群上
- alert - Grafana:如何根据两个事件创建警报?
- c# - 从 OpenApi.json 生成 C# 客户端
- r - 如何使用 ggplot 创建具有共享 x 轴的背靠背图?
- typescript - 如何使用该 xpath 对元素设置操作?
- laravel - Laravel 5.8 请求数据为空