如何避免在STRING_AGG函数SQL Server中重复

时间:2019-09-10 17:22:07

标签: sql sql-server

我正在用SQL测试一个查询,其中我需要以逗号分隔的列表的形式连接值,但它确实有效,只是存在重复值的问题。

这是查询:

SELECT t0.id_marcas                                AS CodMarca, 
       t0.nombremarcas                             AS NombreMarca, 
       t0.imagenmarcas, 
       (SELECT String_agg((t2.name), ', ')
        FROM exlcartu_devcit.store_to_cuisine t1 
               INNER JOIN exlcartu_devcit.cuisine t2 
                       ON t1.cuisine_id = t2.cuisine_id 
        WHERE  store_id = (SELECT TOP 1 store_id 
                           FROM   exlcartu_devcit.store 
                           WHERE  id_marcas = t0.id_marcas 
                                  AND status = 1)) AS Descripcion, 
       t0.logo, 
       t0.imagen, 
       (SELECT TOP 1 preparing_time 
        FROM   exlcartu_devcit.store 
        WHERE  id_marcas = t0.id_marcas 
               AND status = 1)                     AS Tiempo, 
       t0.orden, 
       (SELECT TOP 1 Avg(minimum_amount) 
        FROM   exlcartu_devcit.store_delivery_zone 
        WHERE  id_marcas = t0.id_marcas)           AS MontoMinimo 

FROM   exlcartu_devcit.[marcas] t0 

我认为解决方案可能只是在查询中添加DISTINCT以避免这种方式的重复值...

(SELECT STRING_AGG(DISTINCT (t2.name),  ', ') AS Descripcion

但是显然STRING_AGG()函数不支持它,知道如何避免重复值吗?

1 个答案:

答案 0 :(得分:0)

最简单的方法就是select from select,就像这样:

with dups as (select 1 as one union all select 1 as one)
select string_agg(one, ', ') from (select distinct one from dups) q;

与原始

with dups as (select 1 as one union all select 1 as one)
select string_agg(one, ', ') from dups;