-1

With SQL Server, I would like to pivot or group multiple date columns per id like in the example below:

Four columns from table [db].[exampletable], Id, 1/1, 2/1, 3/1

Id 1/1 2/1 3/1
117 10 5 20
118 5 10 15
119 20 15 15
120 20 20 15

Desired Result:

Id date sum
117 1/1 10
117 2/1 5
117 3/1 20
118 1/1 5
118 2/1 10
118 3/1 15
Dale K
  • 25,246
  • 15
  • 42
  • 71
Starbucks
  • 1,448
  • 3
  • 21
  • 49

2 Answers2

1

One approach uses a union query:

SELECT Id, '1/1' AS date, [1/1] AS sum FROM yourTable UNION ALL
SELECT id, '2/1', [2/1] FROM yourTable UNION ALL
SELECT id, '3/1', [3/1] FROM yourTable
ORDER BY Id, date;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Assuming you have variable or a growing number of columns, you can use a bit of JSON to dynamically UNPIVOT your data without having to use Dynamic SQL

Example or dbFiddle

Select A.[ID]
      ,B.* 
 From  YourTable A
 Cross Apply  (
                 Select [date] = try_convert(varchar(25),[key])
                       ,[sum]  = try_convert(int,Value)
                 From OpenJson(  (Select A.* For JSON Path,Without_Array_Wrapper )  ) 
                 Where [key] not in ('Id','OtherColumns','ToExclude')
              ) B
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66