我有如下表结构
+--------------------------------------+ ID | cmpgn_pic | cmpgn_dt | cmpgn_tg | +--------------------------------------+ |1 | NUSNAFIF | 2015-04-01 | 300000 | |2 | PETERBSG | 2015-04-01 | 30000 | |3 | PTYONG | 2015-04-02 | 700000 | |4 | HMKWAN | 2015-04-01 | 800000 | |5 | NUSNAFIF | 2015-04-05 | 400000 | |6 | NUSNAFIF | 2015-04-02 | 100000 | |7 | HMKWAN | 2015-04-10 | 75000 | |9 | PTYONG | 2015-04-01 | 10000 | |10| PTYONG | 2015-04-05 | 600000 | |11| NUSNAFIF | 2015-04-05 | 600000 | |12| HMKWAN | 2015-04-10 | 800000 | +--------------------------------------+
如何编写动态sql脚本以获得如下所示的结果
+---------------------------------------------------------------------------------------------------------------------------------------------+ | cmpgn_pic | 2015-04-01 | 2015-04-02 | 2015-04-03 | 2015-04-04 | 2015-04-05 | 2015-04-06 | 2015-04-07 | 2015-04-08 | 2015-04-09 | 2015-04-10 | +---------------------------------------------------------------------------------------------------------------------------------------------+ | HMKWAN | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | | NUSNAFIF | 1 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | | PETEGSG | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | PTYONG | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
我只能编写如下的静态mysql脚本
SELECT cmpgn_pic, COUNT(id) FROM t_prebook group by 1
但我不知道如何在我的脚本中显示动态日期。我寻求你的帮助来解决我的问题。 提前谢谢你。
答案 0 :(得分:0)
我认为问题已经回答了一段时间,请参考这个答案。
MySQL pivot row into dynamic number of columns
编辑:MySQL还没有PIVOT功能。您可能的解决方法是创建一个过程,将每个唯一的日期实例附加为新列。