How do I accumulate values in T-SQL? AFAIK there is no ARRAY type.
I want to re-use the values in the same query like demonstrated in this PostgreSQL example using array_agg().
SELECT a[1] || a[i] AS foo
, a[2] || a[5] AS bar -- assuming we have >= 5 rows for simplicity
FROM (
SELECT array_agg(text_col ORDER BY text_col) AS a
, count(*)::int4 AS i
FROM tbl
WHERE id BETWEEN 10 AND 100
) sub;
How would I best solve this with T-SQL?
Best I could come up with are two CTE and subselects:
;WITH x AS (
SELECT row_number() OVER (ORDER BY name) AS rn
, name AS a
FROM #t
WHERE id BETWEEN 10 AND 100
)
, i AS (
SELECT count(*) AS i
FROM x
)
SELECT (SELECT a FROM x WHERE rn = 1) + (SELECT a FROM x WHERE rn = i) AS foo
, (SELECT a FROM x WHERE rn = 2) + (SELECT a FROM x WHERE rn = 5) AS bar
FROM i;
Test setup:
CREATE TABLE #t(
id INT PRIMARY KEY
, name NVARCHAR(100))
;
INSERT INTO #t VALUES
( 3, 'John')
, ( 5, 'Mary')
, ( 8, 'Michael')
, (13, 'Steve')
, (21, 'Jack')
, (34, 'Pete')
, (57, 'Ami')
, (88, 'Bob')
;
Is there a simpler way?
Edit 1: I have added another solution that shows how to simulate ARRAY_AGG on SQL Server (the last answer).
Edit 2: For the solution number 4) I have added the third method for concatenation.
I’m not sure I have I understood correctly your question.
a) Instead of using arrays in SQL Server I would use table variables or XML.
b) To concatenate strings (in this case) I would use
SELECT @var = @var + Name FROM tblstatements orXML xqueries.c) The solution based on CTEs and multiple subqueries (
WITH cte AS () FROM SELECT (SELECT * FROM cte.rn=1) + ()...) will generates a lot of scans and logical reads.Solutions:
1) Table variable +
SELECT @var = @var + Name FROM tbl:2) Table variable +
PIVOT:3) XML + XQuery:
4) If the question is how to simulate
ARRAY_AGGon SQL Server then, one answer might be: by using XML.Example:
Results: