Grouped string aggregation / LISTAGG for SQL Server

http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ It is an interesting problem in Transact SQL, for which there are a number of solutions and considerable debate. How do you go about producing a summary result in which a distinguishing column from each row in each particular category is listed in a ‘aggregate’ column? A simple, and intuitive way of displaying data … Read more

LINQ aggregate and group by periods of time

You could round the time stamp to the next boundary (i.e. down to the closest 5 minute boundary in the past) and use that as your grouping: var groups = series.GroupBy(x => { var stamp = x.timestamp; stamp = stamp.AddMinutes(-(stamp.Minute % 5)); stamp = stamp.AddMilliseconds(-stamp.Millisecond – 1000 * stamp.Second); return stamp; }) .Select(g => new … Read more

SQL comma-separated row with Group By clause

You want to use FOR XML PATH construct: SELECT ACCOUNT, unit, SUM(state_fee), Stuff((SELECT ‘, ‘ + code FROM tblmta t2 WHERE t2.ACCOUNT = t1.ACCOUNT AND t2.unit = t1.unit AND t2.id = ‘123’ FOR XML PATH(”)), 1, 2, ”) [Codes] FROM tblmta t1 WHERE t1.id = ‘123’ GROUP BY ACCOUNT, unit See other examples here: SQL … Read more

Multiple array_agg() calls in a single query

DISTINCT is often applied to repair queries that are rotten from the inside, and that’s often expensive and / or incorrect. Don’t multiply rows to begin with, then you don’t have to fold unwanted duplicates at the end. Joining to multiple n-tables (“has many”) multiplies rows in the result set. That’s efectively a CROSS JOIN … Read more