php - 将 Group By 结果行转换为列 (PHP MYSQL)

标签 php html mysql

我有 table 。

Country Status
USA     A
USA     A
USA     B
USA     C
UK      A
UK      D
UK      D
China   A
China   A
China   C
China   C

我想编写一个查询并将结果显示在如下表中。

Country A   B   C   D   Total
USA     2   1   1   0   4
UK      1   0   0   2   3
China   2   0   2   0   4
Total   5   1   3   2  11

$q="SELECT Country,Status,Count(Status) as Stat Group BY Country,Status";
$r=mysql_query($q);
while($o=mysql_fetch_object($r)){
$t .="<tr>
      <td>$o->Country</td>
      <td>$o->Status</td>
      <td>$o->Stas</td>
      </tr>";
}

它输出。我想要像上面那样。它对国家/地区和状态进行分组,但我不想多次显示国家/地区。我想将 Status 的行输出显示为列并显示它的计数。

USA   A   2
USA   B   1
USA   C   1
UK    A   1
UK    D   2
China A   2
China C   2

最佳答案

您可以通过查询或直接进入 PHP 代码来完成此操作。在查询中,它称为 PIVOTing 表。

这将是:

 select Country, A, B, C, D, (A+B+C+D) Total
   from (
     select Country
            sum(case status = 'A' then 1 else 0 end) as A,
            sum(case status = 'B' then 1 else 0 end) as B,
            sum(case status = 'C' then 1 else 0 end) as C,
            sum(case status = 'D' then 1 else 0 end) as D
       from yourtable
     group by Country
    ) as t

这样做的问题是,对于每个新的状态,您都必须更改查询以添加新的总和

关于php - 将 Group By 结果行转换为列 (PHP MYSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646146/

相关文章:

mysql - find_in_set 和 find_in_set 不起作用

php - 条件语句仅在与最后一条记录不同时显示信息 - PHP - MYSQL

php - 当我加入另一个表时发现查询错误

Javascript : execute a script after location. href

php - 如何使用正则表达式获取所有属性?

javascript - 使用knout js在foreach中添加类别

html - 如何将我的按钮放在 Ruby on rails 的中心?

html - 如何使用 CSS 隐藏特定高度或宽度的 div

MySql 存储过程与匹配

mysql - 获取平均值时在 Ruby + Rails 中执行子查询的最佳方法?