字符串\u agg,带distinct,不带子查询

r3i60tvu  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(454)

这是我的数据

Code    SubCode    Colour     Fruit     Car     City     Name
A       A1         Red        Apple     Honda   Mel      John
A       A1         Green      Apple     Toyota  NYC      John
A       A1         Red        Banana    Honda   Lon      John
A       A1         Red        Banana    Opel    Mel      John
A       A2         ...
A       A2         ...
A       A3
A       A3

这是我的sql

SELECT Code, SubCode, STRING_AGG(Colour, ',') STRING_AGG(Fruit, ',') STRING_AGG(Car, ',') STRING_AGG(City, ',') STRING_AGG(Name, ',')
FROM myTable

我得到这个结果

Code    SubCode    Colour              Fruit                       Car                      City     Name
A       A1         Red,Green,Red,Red   Apple,Apple,Banana,Banan    Honda,Toyota,Honda,Opel  ...

有没有办法让我把价值观区分开来
对于单个值,我可以创建一个子查询 STRING_AGG ?

Code    SubCode    Colour      Fruit           Car                   City     Name
A       A1         Red,Green   Apple,Banana    Honda,Toyota,Opel     ...
wecizke3

wecizke31#

唉,sql server的 string_agg() 目前不支持 DISTINCT . 因此需要多个子查询,例如:

select 
    code, 
    subcode, 
    (select string_agg(color, ',') from (select distinct color from mytable  t1 where t1.code = t.code and t1.subcode = t.subcode) t) colors,
    (select string_agg(fruit, ',') from (select distinct fruit from mytable  t1 where t1.code = t.code and t1.subcode = t.subcode) t) fruits,
    (select string_agg(car  , ',') from (select distinct car   from mytable  t1 where t1.code = t.code and t1.subcode = t.subcode) t) cars,
    (select string_agg(city , ',') from (select distinct city  from mytable  t1 where t1.code = t.code and t1.subcode = t.subcode) t) cities,
    (select string_agg(name , ',') from (select distinct name  from mytable  t1 where t1.code = t.code and t1.subcode = t.subcode) t) names
from mytable t
group by code, subcode

请注意,原始查询缺少 group by 子句,因此它是无效的sql。我也修好了。

zphenhs4

zphenhs42#

悲哀地 string_agg() 不支持 distinct . 但是,使用 row_number() :

SELECT Code, SubCode,
       STRING_AGG(CASE WHEN seqnum_colour = 1 THEN Colour END, ','),
       STRING_AGG(CASE WHEN seqnum_fruit= 1 THEN Fruit END, ','),
       STRING_AGG(CASE WHEN seqnum_car = 1 THEN Car END, ','),
       STRING_AGG(CASE WHEN seqnum_city = 1 THEN City END, ','),
       STRING_AGG(CASE WHEN seqnum_name = 1 THEN Name END, ',')
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY Code, SubCode, Colour ORDER BY Code) as seqnum_colour,
             ROW_NUMBER() OVER (PARTITION BY Code, SubCode, Fruit ORDER BY Code) as seqnum_fruit,
             ROW_NUMBER() OVER (PARTITION BY Code, SubCode, Car ORDER BY Code) as seqnum_car,
             ROW_NUMBER() OVER (PARTITION BY Code, SubCode, City ORDER BY Code) as seqnum_city,
             ROW_NUMBER() OVER (PARTITION BY Code, SubCode, Name ORDER BY Code) as seqnum_name
      FROM myTable t
     ) t
GROUP BY code, subcode;

这是一把小提琴。

相关问题