0

Hey I am not a SQl expert, but I am trying to query data and transpose it and am having trouble, here is what I am wanting:

make this

DateandTime             Val1    Val2
2020-01-01 00:00:00.000  10      20

look like this

DateandTime              Tag       Value
2020-01-01 00:00:00.000  Val1       10
2020-01-01 00:00:00.000  Val2       20

I am not sure what this kind of change this is called in SQL, but any help would be great.

Thanks

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786

2 Answers2

1

This is unpivoting. A generic method is union all:

select dateandtime, 'Val1' as tag, val1 as value
from t
union all
select dateandtime, 'Val2', val2
from t;

Some databases have functionality -- specifically lateral joins -- to make this more efficient.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

In most databases you can use a function called unpivot. Here is an example of it:

select
    *
from TAB_1
unpivot ( value  for tag in (val1, val2))

Results:

+-----------------------+----+-----+
|DATEANDTIME            |TAG |VALUE|
+-----------------------+----+-----+
|2020-01-01 00:00:00.000|VAL1|10   |
|2020-01-01 00:00:00.000|VAL2|20   |
+-----------------------+----+-----+
Simon D
  • 5,730
  • 2
  • 17
  • 31