sql - Get multiple rows as comma separated string column AND map values to temp table from junction table -


i've seen several questions how pull multiple rows single comma-separated column t-sql. i'm trying map examples own case in need bring columns 2 tables referencing junction table. can't make work. here's query have:

with userscsv (useremails, siteid)  (select userssites.siteid, stuff(         (select ', ' + users.email          users          userssites.userid = users.id         xml path ('')         group userssites.userid     ), 1, 2, '')     userssites     group userssites.siteid ) select * userscsv 

the hard stuff here based on this answer. i've added with which, understand it, creates sort of temporary table (i'm sure it's more complicated that, humor me.) hold values. obviously, don't need select values, i'm going joining table later. (the whole of need still more complicated i'm trying here.)

so, i'm creating temporary table named userscsv 2 columns i'm filling selecting siteid column userssites table (which junction table between users , sites) , selecting ', ' + users.email users table should give me email address preceded comma , space. then, chop first 2 characters off using stuff , group whole thing userssites.siteid.

this query gives me error identifying line 5 problem area:

column 'userssites.userid' invalid in select list because not contained in either aggregate function or group clause.

why should matter since column in question in where rather select stated in error? how can fix it? need users id matches id in junction table. i've got tons of users aren't mapped in table , have no need select them.

tl;dr- need temp table distinct sites in 1 column , comma-separated list of email addresses of related users in other. these 2 pieces of data come other tables , put using junction table on primary keys of 2 tables. hope makes sense.

select distinct us.siteid, stuff((select ', ' + u.email         users u          join userssites us2 on us2.userid = u.userid         us2.siteid = us.siteid             xml path('')), 1, 2, '') userssites 

sql fiddle


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -