STRING_AGG 具有不同的无子查询

asm*_*mgx 1 sql sql-server string subquery aggregate-functions

这是我的数据

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
Run Code Online (Sandbox Code Playgroud)

这是我的sql

SELECT Code, SubCode, STRING_AGG(Colour, ',') STRING_AGG(Fruit, ',') STRING_AGG(Car, ',') STRING_AGG(City, ',') STRING_AGG(Name, ',')
FROM myTable
Run Code Online (Sandbox Code Playgroud)

我得到这个结果

Code    SubCode    Colour              Fruit                       Car                      City     Name
A       A1         Red,Green,Red,Red   Apple,Apple,Banana,Banan    Honda,Toyota,Honda,Opel  ...
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的价值观与众不同

对于单个值,我可以创建一个子查询STRING_AGG

Code    SubCode    Colour      Fruit           Car                   City     Name
A       A1         Red,Green   Apple,Banana    Honda,Toyota,Opel     ...
Run Code Online (Sandbox Code Playgroud)

GMB*_*GMB 6

唉,SQL Serverstring_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
Run Code Online (Sandbox Code Playgroud)

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