SQL查询,将表字段移动到列标题

时间:2012-07-16 02:58:01

标签: mysql sql

有没有办法检索这样的数据(第一行是列标题):

data   no    answer
data1  1     X1
data1  2     X2
data1  3     X3
data1  5     X5
data2  1     Y1
data2  2     Y2
data2  4     Y4

以这样的格式(再次,第一行是列标题):

data   no1   no2   no3   no4   no5
data1  X1    X2    X3    null  X5
data2  Y1    Y2    null  Y4    null

使用SQL查询(在MySQL中)?

1 个答案:

答案 0 :(得分:1)

不幸的是,MySQL没有PIVOT功能。所以你必须以另一种方式执行。

使用CASE语句:

select data,
  MIN(CASE WHEN no = 1 THEN answer END) as no1,
  MIN(CASE WHEN no = 2 THEN answer END) as no2,
  MIN(CASE WHEN no = 3 THEN answer END) as no3,
  MIN(CASE WHEN no = 4 THEN answer END) as no4,
  MIN(CASE WHEN no = 5 THEN answer END) as no5
from test
group by data

请参阅SQL Fiddle with Demo