MySql UNION 一行转多列

背景:DataEase饼图有特定格式,并且报表要求全部使用SQL语句获取数据

原先数据格式如下,需要行转换列

MySql UNION 一行转多列_第1张图片

转换后结果:

MySql UNION 一行转多列_第2张图片

原理

字段1,target作为一个不存在的字段,用于命名。
字段2,count字段是关键,将查询结果命名为统一名称,实现行转列。
UNION 拼接三句一样的SQL语句
MySql UNION 一行转多列_第3张图片

更改后SQL

( SELECT "车位总数" AS 'target', total_num AS "count" FROM park_free_space_num ORDER BY report_time DESC LIMIT 1 ) UNION 
( SELECT "已使用车位" AS 'target', (total_num - free_space_num) AS "count" FROM park_free_space_num ORDER BY report_time DESC LIMIT 1 ) UNION
(
	SELECT
		"剩余车位" AS 'target',
		free_space_num AS "count" 
	FROM
		park_free_space_num 
	ORDER BY
		report_time DESC 
	LIMIT 1 
	)

你可能感兴趣的:(数据库技术,mysql,android,数据库)