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

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类