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条)

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要