返回子表

时间:2018-04-24 15:51:50

标签: sql sql-server

我有下表:

|object|attribute1|attribute2|
|A     |true      |10        |
|B     |false     |15        |

我希望有一个返回的查询:

|key      |value    |
|Name_A_1 |true     |
|Name_A_2 |10       |
|Name_B_1 |false    |
|Name_B_2 |15       |

基本上我想将对象的名称转换两次并将其附加到每个属性。

修改

正如Tim Biegeleisen所说,我在这里有类型问题。所以我愿意将所有类型转换为字符串。

3 个答案:

答案 0 :(得分:1)

我会使用apply执行此操作:

select ky, val
from t cross apply
     (values ('Name_' + object + '_1', attribute1),
             ('Name_' + object + '_2', cast(attribute1 as varchar(255)))
     ) v(ky, val);

答案 1 :(得分:0)

 SELECT 'Name_' + object + '_1' as key
        attribute1 as value 
 FROM YourTable
 UNION ALL
 SELECT 'Name_' + object + '_2' as key
        attribute2 as value 
 FROM YourTable

答案 2 :(得分:0)

未经测试,希望这有效......

SELECT 'Name_' + object + '_' + (CAST(row_number() OVER (ORDER BY attribute1, attribute2)) AS VARCHAR(6)) AS row,
   attribute1, 
   attribute2 
FROM tableName