I'm building an SQL query to group and aggregate data. The result should have sum for two decimal fields and comma-delimited varchar field:
┌────┬───────────────┬─────────────┬──────────┬────────┬─────┬─────────────┐
│ Id │ InvoiceNumber │ InvoiceDate │ SellerId │ Amount │ Tax │ InvoiceType │
├────┼───────────────┼─────────────┼──────────┼────────┼─────┼─────────────┤
│ 1 │ a-001 │ 2019-01-11 │ 1 │ 10 │ 2 │ Regular │
│ 2 │ a-002 │ 2019-01-12 │ 1 │ 10 │ 2 │ Regular │
│ 3 │ a-003 │ 2019-01-13 │ 1 │ 10 │ 2 │ Special │
│ 4 │ a-004 │ 2019-01-14 │ 2 │ 10 │ 2 │ Regular │
│ 5 │ a-005 │ 2019-01-15 │ 2 │ 10 │ 2 │ Regular │
│ 6 │ a-006 │ 2019-01-16 │ 3 │ 10 │ 2 │ Special │
└────┴───────────────┴─────────────┴──────────┴────────┴─────┴─────────────┘
Desired output:
┌────┬───────────────┬──────────┬───────────┬────────┬─────┬─────────────────┐
│ Id │ InvoiceNumber │ SellerId │ RowNumber │ Amount │ Tax │ InvoiceType │
├────┼───────────────┼──────────┼───────────┼────────┼─────┼─────────────────┤
│ 3 │ a-003 │ 1 │ 1 │ 30 │ 6 │ Regular,Special │
│ 5 │ a-005 │ 2 │ 1 │ 20 │ 4 │ Regular │
│ 6 │ a-006 │ 3 │ 1 │ 10 │ 2 │ Special │
└────┴───────────────┴──────────┴───────────┴────────┴─────┴─────────────────┘
So far I tried:
SELECT [Id],
[InvoiceNumber],
[SellerId],
ROW_NUMBER() OVER (PARTITION BY [SellerId] ORDER BY [InvoiceDate] DESC) AS [RowNumber],
SUM([Amount]) OVER (PARTITION BY [SellerId]) AS [Amount],
SUM([Tax]) OVER (PARTITION BY [SellerId]) AS [Tax],
STRING_AGG([InvoiceType], ',')
OVER (PARTITION BY [SellerId] ORDER BY [InvoiceType]) AS [InvoiceTypes]
FROM [Invoices]
WHERE [RowNumber] = 1
However, this doesn't work in SQL Server 2012 as it doesn't support the STRING_AGG()
function. Plus I need DISTINCT
values to avoid duplicates in the joined string. Is there any way to accomplish this?
NOTE: the problem is not to concatenate, the problem is to concatenate in a window function.