如何将表列名称作为结果列集中的条目?

时间:2014-02-27 12:42:50

标签: mysql sql

数据库方案包括:

表1(代码,col1,col2,col3,col4,col5)

  1. 怎么做: 对于具有Table1表中最大代码值的Table1,在两列中获取其所有特征(代码除外):
    • 特征的名称(PC表中相应列的名称);
    • 特征的价值。
  2. 我不知道如何在结果列集中获取表列名。 最终结果如下:

    chr value
    col1    133
    col2    80
    col3    28
    col4    2
    col5    50
    

4 个答案:

答案 0 :(得分:1)

这是一项非操作性操作。最简单的方法是使用union all。但是,以下内容通常更有效:

select (case when n.n = 1 then 'col1'
             when n.n = 2 then 'col2'
             when n.n = 3 then 'col3'
             when n.n = 4 then 'col4'
             when n.n = 5 then 'col5'
        end) as chr,
       (case when n.n = 1 then col1
             when n.n = 2 then col2
             when n.n = 3 then col3
             when n.n = 4 then col4
             when n.n = 5 then col5
        end) as value
from table t cross join
     (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
     ) n;

当您的表很大或子查询很复杂时,这会更有效。

union all版本是:

select 'col1', col1 from table t union all
select 'col2', col2 from table t union all
select 'col3', col3 from table t union all
select 'col4', col4 from table t union all
select 'col5', col5 from table t;

答案 1 :(得分:0)

SELECT 'col1', MAX(col1) FROM table1
UNION
SELECT 'col2', MAX(col2) FROM table1
UNION
...

答案 2 :(得分:0)

SELECT 'cd' as chr, cd as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

UNION

SELECT  'model' as chr, cast(model as varchar)as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

UNION

SELECT  'speed' as chr,cast(speed as varchar)  as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

UNION

SELECT  'ram' as chr, cast(ram as varchar) as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

UNION

SELECT  'hd' as chr, cast(hd as varchar)  as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

UNION

SELECT  'price' as chr,cast(price as varchar)  as value 
FROM pc 
WHERE code = (SELECT max(code) FROM pc)

答案 3 :(得分:0)

Select char, value
From 
(Select code,
cast(speed as varchar(20)) speed,
cast(ram as varchar(20)) ram,
cast(hd as varchar(20)) hd,
cast(model as varchar(20)) model,
cast(cd as varchar(20)) cd,
cast(price as varchar(20)) price
FROM pc
) src
UNPIVOT 
(value For char in (speed,ram,hd,model,cd,price)
) As unpvt
where 
code in (Select max(code) from PC)`