我的查询:

select Fimp_date, Fadpos, sum(Fplay_num) as Fplay_num from tbl_cnt_display_num_by_adpos where Fimp_date between date_format(now(),'%Y%m%d')-interval 2 day and date_format(now(),'%Y%m%d') group by Fadpos, Fimp_date;


这是结果:
+ ----------- + -------- + ----------- +

| Fimp_date | Fadpos | Fplay_num |

+ ----------- + -------- + ----------- +

| 20151020 | 0 | 1562156 |

| 20151020 | 1 | 19354 |

| 20151020 | 101 | 352796 |

| 20151020 | 102 | 232052 |

| 20151020 | 103 | 42324 |

| 20151020 | 104 | 214 |

| 20151020 | 105 | 167904 |

| 20151020 | 500 | 49 |

+ ----------- + -------- + ----------- +

如何编写sql让结果转换为:
mysql - mysql查询:将表更改为另一种表现形式-LMLPHP

这意味着每天连续,不同的Fadpos作为不同的列,值是该天Fadpos的Fplay_num。

那么怎么写sql呢?

最佳答案

尝试以下...

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT CONCAT(
      'MAX(CASE WHEN `Fadpos` = ''',
      `Fadpos`,
      ''' THEN Fplay_num END) AS `',
      `Fadpos`, '`'
    )
  ) INTO @sql
FROM (SELECT Fadpos,
             SUM( Fplay_num ) AS Fplay_num
      FROM tbl_cnt_display_num_by_adpos
      WHERE Fimp_date BETWEEN DATE_FORMAT( NOW(), '%Y%m%d' ) - INTERVAL 2 DAY
                          AND DATE_FORMAT( NOW(), '%Y%m%d' )
      GROUP BY Fadpos,
               Fimp_date) AS AliasForSelect;

SET @sql = CONCAT( 'SELECT Fimp_date,
                           ',
                           @sql,
                           '
                    FROM tbl_cnt_display_num_by_adpos
                    GROUP BY Fimp_date;');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


有关更多信息,请参见How to match column names and values from joining and related tables?上我的回答。

请注意,我一直无法测试此代码,因为我需要创建一个示例表并用数据填充它。如果您有执行此操作的脚本,请修改您的问题。失败的话,编辑问题以包括输出的文本副本而不是当前图像会很有帮助。

祝好运!

关于mysql - mysql查询:将表更改为另一种表现形式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33251121/

10-09 09:35