MySQL-将行作为列,将列作为行?

时间:2018-12-17 18:59:18

标签: mysql

如何在MySQL中将行转置为列?

我已经在StackOverflow上阅读了有关此主题的一些问题,但是我仍然不知道如何实现所需的结果。我还尝试了一些代码,但没有成功。

以下示例有望使我想要的结果清楚。我创建了一个按用户ID分组的名为“ summary_kcal”的视图。它的组成如下:

+---------+------+------+------+------+------+------+------+
| userid  |  LU  |  MA  |  ME  |  GIO |  VE  |  SA  | DO   | 
+---------+------+------+------+------+------+------+------+
| 1       | 1000 | 2000 | 1000 | 1500 | 2000 | 1000 | 1500 |
+---------+------+------+------+------+------+------+------+

我想将其转换为:

+---------+---------+
| userid  | 1       |
+---------+---------+
| LU      | 1000    | 
+---------+---------+
| MA      | 2000    | 
+---------+---------+
| ME      | 1000    |
+---------+---------+
| GIO     | 1500    |
+---------+---------+
| VE      | 2000    |
+---------+---------+
| SA      | 1000    |
+---------+---------+
| DO      | 1500    |
+---------+---------+

1 个答案:

答案 0 :(得分:1)

通常最好进行这种转换客户端,但是如果您确实需要在数据库中执行此操作。...

SELECT "LU" AS userid, `LU` AS `1` WHERE userid = 1
UNION
SELECT "MA" AS userid, `MA` AS `1` WHERE userid = 1
UNION
SELECT "ME" AS userid, `ME` AS `1` WHERE userid = 1
UNION
SELECT "GIO" AS userid, `GIO` AS `1` WHERE userid = 1
UNION
SELECT "VE" AS userid, `VE` AS `1` WHERE userid = 1
UNION
SELECT "SA" AS userid, `SA` AS `1` WHERE userid = 1
UNION
SELECT "DO" AS userid, `DO` AS `1` WHERE userid = 1

注意:实际上,您只需要在第一个查询中使用别名,只是为了清楚和一致而包含别名。

如果您想要多个列,每个用户行一个,那么很快就变得难以管理,因为每个XX AS # WHERE userid = #最终都需要成为一个单独的子查询,而不是(或一个笨拙的GROUP CONCAT查询,条件聚集)