doujing3896 2019-06-14 20:10
浏览 74
已采纳

如何在mysql或php中显示动态数据行到数据列?

I have the same problem with (MySQL or PHP Transform rows to columns)[Mysql MySQL or PHP Transform rows to two columns dynamically. But with different header column format.

My database table

enter image description here

i have done with this question, below is my query version:

SELECT GROUP_CONCAT(
      'MAX(IF(day(tanggal) = ',
      day(tanggal),
      ', presensi, NULL)) AS `',
      tanggal,
      '`, '
    order by tanggal
  ) INTO @sql
  FROM tableName;

when running a query it show notification "Query executed OK, 1 row affected.", but result is empty, this is The table expected what looks like

enter image description here

  • 写回答

1条回答 默认 最新

  • dongzhangnong2063 2019-06-15 05:14
    关注

    create your static query:

    select id_pegawai, 
    max(if(tanggal="2019-06-13", presensi, null)) as "2019-06-13",
    max(if(tanggal="2019-06-14", presensi, null)) as "2019-06-14"
    from yourtable
    group by id_pegawai;
    

    create a dinamic query:

      SET @sql = NULL;
        SELECT
         GROUP_CONCAT(
          DISTINCT
            CONCAT(
                'max(if(tanggal="', 
                tanggal, 
                '", presensi, null)) as "',
                tanggal,
                '"'
            )
         ) into @sql
        FROM yourtable;
        SET @sql = CONCAT('SELECT id_pegawai, ',
                            @sql, ' FROM yourtable GROUP BY id_pegawai');
    

    Execute your dinamic query:

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

    inspired from this post: http://buysql.com/mysql/14-how-to-automate-pivot-tables.html

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效