doubianyan9749 2014-02-08 12:46
浏览 7

too long

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
  • 写回答

2条回答 默认 最新

  • duanba8070 2014-02-08 12:58
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)