sql - 选择 SQL 列作为添加的行

标签 sql sql-server sql-server-2008

我有一个 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

非常感谢任何指导。谢谢

最佳答案

另一种方法是像这样使用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

关于sql - 选择 SQL 列作为添加的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38842355/

相关文章:

c# - 在 C# 中格式化 SQL 友好的日期/时间

c# - 在 GridView 的绑定(bind)字段中显示多个数据字段

sql - 用户表到用户和用户首选项。这是标准化的吗?

sql - 在 SQL Server 2005 中使用 MD5 在 varbinary 上执行校验和文件

sql - 使用 T_SQL 将行注入(inject)查询结果

sql - 选择具有最大 ID 和特定条件的行

c# - 需要 SQL Server 2012 Express LocalDB

sql - 为什么在 SSMS 中禁用登录后将用户类型更改为 SQL 用户?

sql - 如何引用第二个 SQL Server

mysql - 通过运行查询来更新表以防止重复记录