How do I select a variable row in SQL Server?

后端 未结 3 1488
时光说笑
时光说笑 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;
    
    0 讨论(0)
  • 2021-01-23 09:26

    This can be done with standard SQL, albeit a bit ugly:

    select i.item, 
           i.year, 
           i.model,
           case i.model 
               when 'MODELA' then p.MODELA 
               when 'MODELB' then p.MODELB 
               when 'MODELC' then p.MODELC 
               when 'MODELD' then p.MODELD 
           end as price
    from Items i INNER JOIN Pricing p ON p.year = i.year
    

    Rextexter demo

    0 讨论(0)
  • 2021-01-23 09:39

    DEMO

    use unpivot and then join to your item table.

    WITH cte as (
        SELECT [Year], [Model], [Price]
        FROM (SELECT [Year], [MODELA], [MODELB], [MODELC], [MODELD]
              FROM pricing) p
        UNPIVOT 
            ([Price] FOR [Model] IN 
                         ([MODELA], [MODELB], [MODELC], [MODELD])
            ) as unpvt
    ) 
    SELECT i.*, c.price
    FROM cte c
    JOIN items i 
      ON c.[Year] = i.[Year]
     AND c.[Model] = i.[model]
    

    OUTPUT

    0 讨论(0)
提交回复
热议问题