I wanna know how to exclude specific string in STRING_AGG? Here's my original query I want to exclude from the concatenation for a specific value on column name PRIMARY. Sorry I don't know how to use correct format, I will attach image instead for clear picture of my scenario.
SELECT t1.ID, t1.NAME, STRING_AGG(Trim(t2.COUNTRY), ';') WITHIN GROUP(ORDER BY COUNTRY) COUNTRY, PRIMARY FROM t1 LEFT JOIN t2 on t1.ID=t2.ID GROUP BY t1.ID,t1.NAME,t1.PRIMARY
t1
ID NAME PRIMARY 1 WHITE US 2 RED CA 3 BLUE US 4 GREEN GB
t2 ID COUNTRY 1 US 1 CA 2 GB 2 DE 3 DE 3 CA 4 CA 4 DE 4 US
RESULT: ID NAME PRIMARY COUNTRY 1 WHITE US CA (EXCEPT US BECAUSE IT'S ALREADY IN PRIMARY) 2 RED CA GB;DE
3 BLUE US DE;CA
4 GREEN DE CA;DE;US (EXCEPT DE BECAUSE IT'S ALREADY IN PRIMARY)
Just use a case
expression:
STRING_AGG(CASE WHEN t2.Country <> Primary THEN Trim(t2.COUNTRY) END, ';') WITHIN GROUP (ORDER BY COUNTRY)
STRING_AGG()
ignores NULL
values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.