简体   繁体   中英

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. On a query it is called PIVOTing table.

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 .

I also have the same need, here is the sql which i got the result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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