如何在mysql中进行数据透视查询?

时间:2015-10-06 07:09:57

标签: mysql sql pivot-table

我有一个表criteria,其结构如下:

+----------+------+-------+
| criteria | user | total |
+----------+------+-------+
| xxxxxxxx | xx   | xxx   |
+----------+------+-------+

我在创建查询时遇到问题。我想从单个表中进行数据透视查询,我有这些数据:

+----------+------+-------+
| criteria | user | total |
+----------+------+-------+
|    F1    |  A1  |  17   |
|    F2    |  A1  |  9    |
|    F3    |  A1  |  6    |
|    F4    |  A1  |  4    |
|    F1    |  A2  |  19   |
|    F2    |  A2  |  6    |
|    F3    |  A2  |  2    |
|    F4    |  A2  |  8    |
+----------+------+-------+

我希望像这样建立查询枢轴:

+----------+------+-------+------+-------+
| criteria | user | total | user | total |
+----------+------+-------+------+-------+
|    F1    |  A1  |  17   |  A2  |  19   |
|    F2    |  A1  |  9    |  A2  |  6    |
|    F3    |  A1  |  6    |  A2  |  2    |
|    F4    |  A1  |  4    |  A2  |  8    |
+----------+------+-------+------+-------+    

有人可以帮我写一个查询来获得上述结果吗?

1 个答案:

答案 0 :(得分:3)

您的问题似乎可以通过自我加入而不是支点来处理。您可以使用JOINcriteriacriteria表放在一起:

SELECT c1.criteria AS criteria, c1.user AS user, c1.total AS total,
    c2.user AS user, c2.total AS total
FROM criteria c1 INNER JOIN criteria c2
ON c1.criteria = c2.criteria
WHERE c1.user < c2.user