Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a table A and table B.

tableA

id  columnnamesA  

1    col1
2    col2
3    col3


tableB

daterpt     col1  col1 col3
29-01-2015   45    55   12



Now i was trying to get the result in this format.

id columnnamesA    value
1     col1         45
2     col2         55
3     col3         12


-- i tried some approach and was able to ahieve it..but i thought to try in this way


select id,columnname,(select columnname from tableB where daterpt='29-01-2015')
from tableA

but this doesnt work. Is there a way to achieve it as above. Please suggest
Posted
Comments
Tomas Takac 3-Feb-16 2:44am    
You need to unpivot tableB then join to tableA. If the set of columns is not fixed then you need to employ dynamic sql to unpivot it.
Herman<T>.Instance 3-Feb-16 3:36am    
Exactly. The only option is to UNPIVOT

1 solution

Try with below SQL query:
SQL
create table tableA(id int, columnname varchar(10));
INSERT INTO tableA VALUES(1, 'col1');
INSERT INTO tableA VALUES(2, 'col2');
INSERT INTO tableA VALUES(3, 'col3');

create table tableB(daterpt datetime, col1 int, col2 int, col3 int);
INSERT INTO tableB VALUES('10-10-2016', 45, 55, 12);

select temp1.id, temp1.column, temp2.value from tableA temp1
INNER JOIN (select u.column, u.value
from tableB s
unpivot
(
  value
  for column in (col1, col2, col3)
) u) as temp2
ON temp1.column = temp2.column;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900