从表中输出矩阵视图

时间:2016-03-19 08:50:11

标签: php mysql

我是新手,请帮助我, 我在表格中有4列的数据,如下所示:

+---------------------+
| id  ah  av  score   |
+---------------------+
| 1   A   A    1      |
| 2   A   B    2      |
| 3   B   A   0.5     |
| 4   B   B   0.14    |
+---------------------+

我想输出类似这样的查询结果

+-------------------+
| Type   A    B     |
+-------------------+
| A      1    2     |
| B      0.5  0.14  |
+-------------------+

2 个答案:

答案 0 :(得分:1)

您的问题需要一个数据透视表,因为您正在“旋转”其中一列成为一行。

首先使用您需要的所有数据创建一个视图(几乎忽略了ID):

create view Scores_Simple as (
select
   ah as Type,
   case when av = "A" then Score end as A,
   case when av = "B" then Score end as B
from Scores
);

然后转动表格:

create view Scores_Simple_Pivot as (
select
   Type,
   sum(A) as A,
   sum(B) as B
from Scores_Simple
group by Type
);

Tested here

答案 1 :(得分:1)

angular           = window.angular || (window.angular = {})