有没有办法检索这样的数据(第一行是列标题):
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中)?
答案 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