Note that there are some explanatory texts on larger screens.

plurals
  1. POSql query to return elements with same ID as comma separated string
    primarykey
    data
    text
    <p>I have two tables, <code>table1</code> has a <code>entry_ID</code>, <code>entry_date</code> and other entry information. <code>table2</code> has <code>entry_ID</code> and <code>entry_subject</code>. Each <code>entry_ID</code> can have arbitrarily many <code>entry_subjects</code>.</p> <p>I want a query that will return an <code>entry_ID</code>, <code>entry_date</code>, and a list of the subjects corresponding to that entry separated by commas. </p> <p>The first step in this seems to be just getting a query that returns an <code>entry_ID</code> and a comma separated list of subjects from <code>table2</code>. Once I have that the join should be easy.<br> I adapted the <a href="http://www.projectdmx.com/tsql/rowconcatenate.aspx" rel="nofollow">recursive CTE method from this site</a>: to fit my case:</p> <pre><code>WITH RECURSIVE CTE (entry_ID, subjectlist, subject, length) AS ( SELECT entry_ID, cast( '' as varchar(8000)) , cast( '' as varchar(8000)), 0 FROM table2 GROUP BY entry_ID UNION ALL SELECT t2.entry_ID, cast(subjectlist || CASE length = 0 THEN '' ELSE ', ' END || entry_subject AS varchar(8000) ), cast (t2.entry_subject as varchar(8000)), length +1 FROM CTE c INNER JOIN table2 t2 on c.entry_ID=t2.entry_ID where t2.entry_subject &gt; c.subject) SELECT entry_ID, subjectlist FROM ( SELECT entry_ID, subjectlist, RANK() OVER ( PARTITION BY entry_ID order by length DESC) FROM CTE) D (entry_ID, subjectlist, rank) where rank = 1; </code></pre> <p>And it works, I get the response I expect. To achieve my final goal the query I use is this:</p> <pre><code>SELECT t1.* t2.subjectlist FROM table1 JOIN (ABOVE QUERY) AS t2 on t1.entry_ID=t2.entry_ID; </code></pre> <p>This seems very unwieldy. Is this really the best way to do this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload