doufu9947 2013-12-18 04:01
浏览 20
已采纳

如何从mySQL表中分组/总数据? [关闭]

I have a table in the database that I want to perform a mySQL query on. Here's what the table looks like:

https://docs.google.com/spreadsheet/ccc?key=0At5_g34zSM41dFlNWUdNQnRPandiUUFuaUJzTEc1REE&usp=sharing

Given this table, I want to display the total number/count of users per journey and goalname.

I've tried to use GROUP BY and COUNT but what I only get is this:

enter image description here

As you can see, the data is only grouped by goalname. Is there a way where I could achieve this kind of result through mySQL query:? (see image below)

enter image description here

Something like this. I hope you could help me with this. Thanks in advance!

  • 写回答

3条回答 默认 最新

  • douao1579 2013-12-18 04:55
    关注

    What you need is to PIVOT the columns into rows. Unfortunately, MySQL has no PIVOT table operator. But you can use the CASE expression to do this, like -

    SELECT
      journey,
      SUM(CASE WHEN  goalname = 'Frank.net Hospital Cash Back' THEN count END) AS `Frank.net Hospital Cash Back`,
      SUM(CASE WHEN  goalname = 'Frank.net Life Cover' THEN count END) AS `Frank.net Life Cover`,
      SUM(CASE WHEN  goalname = 'Frank.net Salary Protection' THEN count END) AS `Frank.net Salary Protection`,
      SUM(CASE WHEN  goalname = 'King Price Car Insurance' THEN count END) AS `King Price Car Insurance`
    FROM test
    GROUP BY journey;
    

    SQLFiddle example - http://sqlfiddle.com/#!2/314c6/8

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow