您可以使用
GROUP BY和
MAX模拟枢轴。MySQL还支持
IF语句。
SELECt ID, MAX(IF(`order` = 1, data, NULL)) data1, MAX(IF(`order` = 2, data, NULL)) data2FROM TableAGROUP BY ID
- SQLFiddle演示
如果您有多个值
order,则动态SQL可能更合适,这样您就不必修改查询:
SET @sql = NULL;SELECt GROUP_CONCAt(DISTINCT CONCAt( 'MAX(IF(`order` = ', `order`, ',data,NULL)) AS data', `order`) ) INTO @sqlFROM TableName;SET @sql = CONCAt('SELECt ID, ', @sql, ' FROM TableName GROUP BY ID');PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;
- SQLFiddle演示
- SQLFiddle演示( 另一个示例 )
两个查询的输出:
╔════╦═══════╦═══════╗║ ID ║ DATA1 ║ DATA2 ║╠════╬═══════╬═══════╣║ 1 ║ P ║ S ║║ 2 ║ R ║ Q ║╚════╩═══════╩═══════╝
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)