sql - SQL Select,是否可以根据键将特定的重复行合并为 1?
问题描述
我对此有点困惑。我有一个如下所示的表:
Group_Key Trigger_Type Event_Type Result_Id
1 A A 1
2 B B 2
3 C C 3
3 C C 4
4 E E 5
5 F F 6
5 F F 7
有些行将具有相同的调查(除 result_id 外,所有列都应相同)键,但它们将具有不同的 result_Id。是否可以在获取行的表上进行选择,而不是因为 result_id 而返回 2 行,而是将那些具有欺骗性的行分组到一行中,其中 result_id 是一个连接字符串?例如,返回这个:
Group_Key Trigger_Type Event_Type Result_Id
1 A A 1
2 B B 2
3 C C 3,4
4 E E 5
5 F F 6,7
这可能吗?
谢谢,
解决方案
这是一个使用递归 CTE 复制string_agg()
. 此示例来自execsql 的 upsert 脚本,由 Elizabeth Shea 编写。必须根据您的特定用途对其进行修改,用您自己的列名替换 execsql 变量引用。
if object_id('tempdb..#agg_string') is not null drop table #agg_string;
with enum as
(
select
cast(!!#string_col!! as varchar(max)) as agg_string,
row_number() over (order by !!#order_col!!) as row_num
from
!!#table_name!!
),
agg as
(
select
one.agg_string,
one.row_num
from
enum as one
where
one.row_num=1
UNION ALL
select
agg.agg_string + '!!#delimiter!!' + enum.agg_string as agg_string,
enum.row_num
from
agg, enum
where
enum.row_num=agg.row_num+1
)
select
agg_string
into #agg_string
from agg
where row_num=(select max(row_num) from agg);
推荐阅读
- c# - C# Linq 计算具有特定值的 XML 段
- search - 自定义域搜索栏 WHMCS 集成
- sql - 如何在数据集中获得每小时?
- c# - 如何更改 ReadAsync 返回的数据格式以使用 dataTables?
- fb-hydra - 如何从以前的作业中加载 Hydra 参数(无需使用 argparse 和 compose API)?
- load-testing - 不能从 Locust 生成超过 ~8000 RPM
- json - JSLT:不是通过索引而是通过表达式访问或查询数组元素
- css - 使用 esc 键离开焦点后的按钮轮廓
- javascript - Vega-lite:您如何自定义图例标签?
- javascript - 面对验证码时如何编写python selenium代码