SQL选择查询以从同一行中提取多个值作为单个行

时间:2012-06-26 14:44:18

标签: sql db2

我有一个存储位置值的数据表: CTY_CD,STATE_CD,COUNTRY_CD和我想从这个表中选择给定城市代码,并选择所有三个位置代码作为单独的行,另一列显示它是什么样的位置类型,因此查询的结果如下所示:

Given city code DEN:

Type         |    Code
CTY_CD            DEN
STATE_CD          CO
COUNTRY_CD        US

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

这样的事情?

 select 'CTY_CD' AS Type,  CTY_CD AS Code FROM tableName WHERE CTY_CD = 'DEN'
 UNION
 select 'STATE_CD' AS Type, STATE_CD AS Code FROM tableName WHERE CTY_CD = 'DEN'
 UNION
 select 'COUNTRY_CD' AS Type, COUNTRY_CD AS Code FROM tableName WHERE CTY_CD = 'DEN'