0

How to convert unknown values in column to row with fixed column and sum value in another column in SQL Server?

This example

   | Id | Date | Amount1 | Amount2
   +----+------+---------+--------
   | 1  | 2018 | 1000    | 100
   | 2  | 2018 | 2000    | 200
   | 2  | 2018 | 3000    | 300
   | 1  | 2019 | 4000    | 400
   | 1  | 2019 | 5000    | 500
   | .. | .... | ....    | ...

I want this

| Id | 2018Amount1 | 2018Amount2 | 2019Amount1 | 2019Amount2 | ...
+----+-------------+-------------+-------------+-------------+-------
| 1  |    1000     |     100     |   9000      |   900       | ...
| 2  |    5000     |     500     |   0         |   0         | ...
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
super.Omar
  • 31
  • 4

2 Answers2

1

Use conditional aggregation :

select Id, 
       sum( case when Date = 2018 then Amount1 end ) as "2018Amount1",
       sum( case when Date = 2018 then Amount2 end ) as "2018Amount2",
       sum( case when Date = 2019 then Amount1 end ) as "2019Amount1",
       sum( case when Date = 2019 then Amount2 end ) as "2019Amount2" 
  from tab
 group by Id
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
Barbaros Özhan
  • 47,993
  • 9
  • 26
  • 51
1

You can use dynamic pivot

DECLARE @ColName NVARCHAR(MAX) =''
SELECT @ColName = @ColName + ', '+ ColName
FROM (  SELECT  DISTINCT  QUOTENAME( CAST([Date] AS VARCHAR(4)) + 'Amount1') 
            + ', ' + QUOTENAME(CAST([Date] AS VARCHAR(4)) + 'Amount2') ColName FROM TestTable )T

SET @ColName = STUFF (@ColName,1,1,'')

DECLARE @SqlText NVARCHAR(MAX) = 
'SELECT * FROM (
    SELECT Id, CAST([Date] AS VARCHAR(4)) + ''Amount1'' AS [Date], Amount1 AS Amount FROM TestTable
    UNION 
    SELECT Id, CAST([Date] AS VARCHAR(4)) + ''Amount2'' [Date], Amount2 AS Amount FROM TestTable
) SRC
PIVOT(SUM(Amount) FOR Date IN (' + @ColName+ ') ) AS PVT'

EXECUTE sp_executesql @SqlText
Serkan Arslan
  • 12,740
  • 4
  • 28
  • 42