Frustratingly, I\'m working with a table where the row name should be a value. How can I select that row in SQL Server based on a value? I\'m aiming at something that looks like
What a bad design :( Anyway, you can do what you want in a number of ways and one way is to use UNPIVOT:
declare @t1 table (item varchar(10), year int, model varchar(10));
insert @t1 (item,year,model) values
('xx',2001,'MODELC'),
('yy',2002,'MODELA'),
('zz',2002,'MODELD');
declare @t2 table (year int, modela int, modelb int, modelc int, modeld int);
insert @t2 (YEAR, MODELA, MODELB, MODELC, MODELD) values
(2000,100 ,101 ,102 ,103 ),
(2001,205 ,206 ,250 ,300 ),
(2002,1000,1200,1500,1700);
with up as
(
select year, v, model
from
(select YEAR, MODELA, MODELB, MODELC, MODELD from @t2) p
unpivot
(v for model in (MODELA, MODELB, MODELC, MODELD)) as unp
)
select t1.*, up.v from @t1 t1 inner join up on t1.year = up.year and t1.model = up.model;