首页 > 解决方案 > 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

这可能吗?

谢谢,

标签: sqlsql-server

解决方案


这是一个使用递归 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);

推荐阅读