简体   繁体   English

将“按结果分组”行转换为列(PHP MYSQL)

[英]Convert the Group By Result row into column (PHP MYSQL)

I have 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

I want to write a query and display the result in table like below. 我想编写一个查询并在如下表中显示结果。

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>";
}

It outputs. 输出。 Which I want like above. 我想要上面的。 It groups the country and status but i don't want to display country multiple times. 它将国家和状态分组,但我不想多次显示国家。 and i want to display the row output of Status as column and display it counts. 我想将状态的行输出显示为列并显示其计数。

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

You can do this either by query or direct into php code. 您可以通过查询或直接进入php代码来执行此操作。 On a query it is called PIVOTing table. 在查询中,它称为PIVOTing表。

it would be: 这将是:

 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

The problem with this is that to every new status you will have to change your query adding a new sum . 问题在于,对于每个新status您都必须更改查询以添加新的sum

I also have the same need, here is the sql which i got the result: 我也有同样的需要,这是我得到的结果的SQL:

SELECT practiceCode, A, B, C, D, (A+B+C+D) Total
FROM (
   SELECT practiceCode,
        SUM(CASE WHEN TYPE = 1 THEN 1 ELSE 0 END) AS A,
        SUM(CASE WHEN TYPE = 2 THEN 1 ELSE 0 END) AS B,
        SUM(CASE WHEN TYPE = 3 THEN 1 ELSE 0 END) AS C,
        SUM(CASE WHEN TYPE = 4 THEN 1 ELSE 0 END) AS D
   FROM laborder
   GROUP BY practiceCode, TYPE
) AS t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM