I have a table like
att1 att2 att3 att4
-------------------
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
What is the query to get the table as a coordinate system as:
a b val
-------
1 1 1
1 2 6
1 3 11
1 4 16
2 1 2
2 2 7
2 3 12
2 4 17
3 1 3
3 2 8
3 3 13
3 4 18
4 1 4
4 2 9
4 3 14
4 4 19
Currently I have:
select 1,att1 from data_journal_insurance_raw union all
select 2,att2 from data_journal_insurance_raw union all
select 3,att3 from data_journal_insurance_raw union all
select 4,att4 from data_journal_insurance_raw
I am missing the ‘b’ part how to do it?
If I understand you correctly, you want to convert the table into a table containing Row, Column and Value.
Actually, you’re missing the
apart.arepresents the row, andbthe column. The following query should help you.Notice that I’m casting the value column to
VARCHAR(MAX), because I don’t know what data types you have in your table. If they’re all numeric, then you can drop theCASTfunctions.If you’re only doing this once on a single table, then this will work fine for you. However, if you want to be able to do this on various tables, you can make SQL Server write the code for you. Here’s a procedure that will do just that: