我有这样的表结构
id | fieldno | fieldvalue Id|taxper|value
1 | 10 | 2 | 0 | 100
1 | 20 | 2 | 5 | 110
1 | 30 | 2 | 10| 200
1 | 40 |
所需的输出,如
id 0% 5% 10 %
1 100 110 200
我想将行组合成不同的列
答案 0 :(得分:0)
对于当前的样本数据,它是一个简单的支点案例:
select
id,
max(if(taxper=0, value, null)) as `0%`,
max(if(taxper=5, value, null)) as `5%`,
max(if(taxper=10, value, null)) as `10%`
from table1
group by id
如果taxper
有很多值,那么您可能需要这样:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(taxper = ''',
taxper,
''', value, NULL)) AS `',
taxper, '%`'
)
) INTO @sql
FROM Table1;
SET @sql = CONCAT('SELECT id, ', @sql, ' FROM Table1 GROUP BY id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;