How do I select a variable row in SQL Server?

后端 未结 3 1491
时光说笑
时光说笑 2021-01-23 08:56

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

3条回答
  •  悲&欢浪女
    2021-01-23 09:26

    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;
    

提交回复
热议问题