我有 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/