STRING_AGG 按多列分组

问题描述 投票:0回答:3

我有一个返回这个的sql查询:

id LS_NoSerie DO_Tiers rn 总匹配
1 A I607 1 80
2 A I3446 2 80
3 A I3446 3 80
4 I3446 1 60
5 A4123 2 60
6 B7856 3 60

注意这里我们有:

  • 2个不同的
    LS_NoSerie
    361843
    564124
  • rn
    对应于ROW_NUMBER
    LS_NoSerie

我想在此结果之上执行查询以获得此:

id LS_NoSerie DO_Tiers rn 总匹配
1 A I607,I3446,I3446 1 80
4 I3446,A4123,B7856 1 60

基本上我想要

rn
= 1和
DO_Tiers
的所有行都得到相应
LS_NoSerie
的聚合字符串。

类似的东西:

SELECT cte.id, cte.LS_NoSerie, STRING_AGG(CONCAT(cte.DO_Tiers, ''), ','), cte.rn, cte.totalMatch
FROM (
         SELECT * FROM my_table_name
     ) as cte
WHERE cte.rn = 1
GROUP BY cte.LS_NoSerie

但它不起作用,因为

cte.id
cte.LS_NoSerie
cte.rn
cte.totalMatch
不是聚合,也不是
GROUP BY
的一部分。

如果你想复制:

CREATE TABLE my_table_name
(
    id         INT,
    LS_NoSerie VARCHAR(255),
    DO_Tiers   VARCHAR(255),
    rn         INT,
    totalMatch INT
);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (1, N'A', N'I607', 1, 80);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (2, N'A', N'I3446', 2, 80);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (3, N'A', N'I3446', 3, 80);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (4, N'B', N'I3446', 1, 60);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (5, N'B', N'A4123', 2, 60);

INSERT INTO my_table_name (id, LS_NoSerie, DO_Tiers, rn, totalMatch)
VALUES (6, N'B', N'B7856', 3, 60);
sql sql-server aggregate-functions greatest-n-per-group
3个回答
2
投票

您可以使用条件聚合从每组中的 rn=1 行中获取值:

SELECT 
  MAX(CASE WHEN rn = 1 THEN id END) AS id, 
  ls_noserie,
  STRING_AGG(CONCAT(do_tiers, ''), ',') AS tiers,
  1 AS rn, 
  MAX(CASE WHEN rn = 1 THEN totalmatch END) AS totalmatch
FROM my_table_name
GROUP BY ls_noserie
ORDER BY ls_noserie;

演示:https://dbfiddle.uk/-XMD6EDg


2
投票

查看您的样本数据只需一些简单的聚合就可以让您到达那里:

select
  Min(Id),
  LS_NoSerie, 
  String_Agg(DO_Tiers, ',') DO_tiers, 
  Min(rn) rn,
  Min(totalMatch) totalMatch
from t
group by LS_NoSerie;

0
投票

这是分组查询

SELECT 
        min( cte.Id) as Id
        , cte.LS_NoSerie as LS_NoSerie
        , STRING_AGG(CONCAT(cte.DO_Tiers, ''), ',') WITHIN GROUP (ORDER BY cte.Id)   as DO_Tiers
        ,1 rn
        ,Max(cte.totalMatch) as totalMatch 
FROM my_table_name cte
GROUP BY cte.LS_NoSerie
order by id
© www.soinside.com 2019 - 2024. All rights reserved.