【问题标题】:Select SQL Columns as added rows选择 SQL 列作为添加的行
【发布时间】:2016-12-15 00:06:58
【问题描述】:

我有一个如下的 SQL Server 2008 表...

ID    Others1Desc    Others1Value    Others2Desc    Others2value
--    -----------    ------------    -----------    ------------
id_x  xyz            12.50           pqr            10.00
id_y  abc            NULL            mno             1.05

现在,我想要如下的选择结果...

ID    ItemDesc       ItemValue
--    -----------    ------------
id_x  xyz            12.50
id_x  pqr            10.00
id_y  abc             NULL
id_y  mno             1.05

非常感谢任何指导。谢谢

【问题讨论】:

    标签: sql sql-server sql-server-2008


    【解决方案1】:

    另一种方法是像这样使用cross applyvalues clause

    DECLARE @temp table (ID [varchar](100), Others1Desc [varchar](100), Others1Value decimal(11, 2), Others2Desc [varchar](100), Others2Value decimal(11, 2));
    
    INSERT @temp (ID, Others1Desc, Others1Value, Others2Desc, Others2Value) VALUES ('id_x', 'xyz', 12.50, 'pqr', 10.00);
    INSERT @temp (ID, Others1Desc, Others1Value, Others2Desc, Others2Value) VALUES ('id_y', 'abc', NULL, 'mno', 1.05);
    
    select ID, t.* from @temp
    cross apply
    (
        values (Others1Desc, Others1Value),
                (Others2Desc, Others2Value)
    ) t(ItemDesc, ItemValue)
    

    结果

    ID     ItemDesc  ItemValue
    --------------------------
    id_x    xyz       12.50
    id_x    pqr       10.00
    id_y    abc       NULL
    id_y    mno       1.05
    

    【讨论】:

    • 今天学到了一些东西。 :)
    【解决方案2】:

    您可以使用UNION ALL 来执行此操作:

    select ID, Others1Desc as ItemDesc, Others1Value as ItemValue
    from yourtable
    union all
    select ID, Others2Desc as ItemDesc, Others2Value as ItemValue
    from yourtable
    

    【讨论】:

      【解决方案3】:

      这边:

      select ID, Others1Desc as ItemDesc,Others1Value as itemValue from
      (select ID ,   Others1Desc ,   Others1Value from table1
      
      Union all
      
      select ID ,   Others2Desc,   Others2value from table1)as a
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        • 2020-10-24
        相关资源
        最近更新 更多