dongwei2610 2012-10-10 09:57
浏览 67
已采纳

GROUP BY用作列的行上的某个值

I have a table of survey data where lines of results are separated into many rows by, each having their own variable name.

My table looks like this:

data_id  data_content   var_name          var_line
1        1              SERIAL            1
2        2              GND.AGE           1
3        3              GND.NEWS.FREQ     1
4        2              SERIAL            2
5        3              GND.AGE           2
6        3              GND.NEWS.FREQ     2
7        3              SERIAL            3
8        3              GND.AGE           3
9        4              GND.NEWS.FREQ     3

Here is my current query to retrieve the total number of answers for every possible answer of GND.NEWS.FREQ. As in the total number:

SELECT *, COUNT(*) as total
  FROM `data`
 WHERE `var_name` = 'GND.NEWS.FREQ'
 GROUP BY `data_content`

Now I need to add the functionality to only return answers where GND.AGE for example is 3. So basically treat all rows where var_line = 1 as a single row.

I have looked up pivot tables but I'm not sure how to add that into my current query.

I would like to do this in one query if possible but I wouldn't mind doing something like getting var_line IDs in a separate query.

  • 写回答

1条回答 默认 最新

  • dongquming3255 2012-10-10 10:16
    关注

    Unfortunately MySQL does not have a PIVOT function which is basically what you are trying to do. So you will need to use an aggregate function with a CASE statement. If you have a unknown number of var_name values that you want to turn into columns, then you can use prepared statements:

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'max(case when var_name = ''',
          var_name,
          ''' then var_line end) AS ',
          replace(var_name, '.', '_')
        )
      ) INTO @sql
    FROM data;
    
    SET @sql = CONCAT('SELECT data_content,', @sql, ' 
                      from data
                      group by data_content
                      ');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    See SQL Fiddle with Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题