Is there such a thing as a join() aggregate function that concatentates field values at a specific character?
Let's say I have a table called cities with fields of state and city. Data looks like this: State City Ohio Eaton Ohio Columbus Ohio Dayton Ohio Greenville New York New York New York Albany New York Syracuse I would like to be able to do this: select state, join(city,',') from cities group by state ...to return this: State City Ohio Eaton,Columbus,Dayton,Greenville New York New York,Albany,Syracuse Would I need to create some crazy UDF for this? If there's not a function, is there a way to apply some SQL magic to make this happen?
A recursive CTE should be able to accomplish this. I mocked up the sequence number to reset for each State. You may have to tweak this based on your actual table but it should at least get you thinking in the right direction. (Similar to what Marc B linked on the Teradata Forum but hopefully this is easier to read.) WITH RECURSIVE city_list (state, cities, seq) AS ( SELECT s.state , s.city , ROW_NUMBER() OVER (PARTITION BY State ORDER BY State, City) AS seq FROM states s QUALIFY seq = 1 UNION ALL SELECT c.cities ||’, ’|| s.city , ROW_NUMBER() OVER (ORDER BY State, City) AS seq FROM city_list c, states s WHERE s.seq = c.seq + 1 AND s.state = c.state ) SELECT r.state, r.cities FROM city_list r WHERE r.seq = (SELECT MAX(h.seq) FROM city_list h WHERE h.state = r.state GROUP BY h.state) ;
Aggregations With Geomesa
incomplete results with aggregate (R)
How to do an aggregated OR on a column in Amazon Redshift
'Your query does not include the specified expression as part of an aggregate function' error for calculated fields
Creating percentile_cont as aggregate function in Vertica
Create Expression in Report Builder 3.0 Report to sum a column
SAP Hana - STRING_AGG issue with ORDER BY CLAUSE
rrdtool does not keep max
Tableau Aggregate Percentage
use aggregates (min, max, avg) in CONSTRUCT query [duplicate]
R: transposing and aggregating columns
SQL Query Aggregate Error
Usage of aggregate functions in MarkLogic
Querying customDimensions in Google Bigquery
NHibernate - QueryOver criteria appearing in Where instead in Having clause, error
Howto aggregate on full data set in Spring Batch jobs?