Transpose Rows to Headers in MYSQL

冷暖自知 提交于 2019-12-30 11:54:48

问题


I'm trying to transpose a very basic output for use in a web application. As my strengths lie moreso in mysql, I'd like to this before it hits the app.

What I currently have is:

date          value
2012-01-01    23
2012-01-02    33
2012-01-03    56
2012-01-04    10

What I want is:

2012-01-01  2012-01-02  2012-01-03  2012-01-04
23          33          56          10

My sql is:

SELECT

date,
value
from values
where date >= curdate() - interval 3 day

I've done a ton of research online and I can't figure out a good way to do this. This would need to be dynamic as the dates do change daily.


回答1:


Here's a dynamic sql to pivot records,

SET @sql = NULL;

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN date = ''',
               date,
               ''' THEN Value ELSE NULL END) AS ',
               CONCAT('`', date, '`')
               )) INTO @sql
FROM TableName
// WHERE date >= curdate() - interval 3 day  // add condition here
ORDER BY date;



SET @sql = CONCAT('SELECT ', @sql, ' 
                   FROM TableName');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
  • SQLFiddle Demo


来源:https://stackoverflow.com/questions/16619784/transpose-rows-to-headers-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!