PHP动态数据透视表

时间:2015-02-20 21:10:57

标签: php mysql

我的例子在这里:http://sqlfiddle.com/#!2/c8f7d/1
1.我如何在php中集成它,以便我可以在我的网站上显示它,我的意思是在一个类似于上面链接中的表格。
2.我的第二个问题是关于日期字段,如果我不把日期放在双引号之间“,我在网站上得到了Mysql错误”sql fiddle“(见上面的例子)

SQL代码:

create table volunteer  
(  
  vol_id int,  
  vol_giv_name varchar(15),  
  vol_fam_name varchar(15),  
  PRIMARY KEY (`vol_id`)  

);  
insert into volunteer values  
(1, 'Jack', 'Napper'),  
(2, 'Sylvie', 'Tingle'),  
(3, 'Floy', 'Stambaugh');  


create table volunteer_attendance  
(  
  att_id int,  
  vol_id int,  
  att_date date NOT NULL,  
  vol_att char(1),  
  PRIMARY KEY (`att_id`)  
);  
insert into volunteer_attendance values  
(1,  '2', '2015-01-03', 'P'),  
(2,  '1', '2015-01-10', 'A'),  
(3,  '1', '2015-01-17', 'P'),  
(4,  '2', '2015-01-24', 'A'),  
(5,  '3', '2015-01-24', 'P');  

--- Query  
SET @sql = NULL;  
SELECT  
  GROUP_CONCAT(DISTINCT  
    CONCAT(  
      'MAX(IF(va.att_date = ''',  
      att_date, 
      ''', va.vol_att, NULL)) AS ',  
      att_date    
    )  
  ) INTO @sql  
FROM volunteer_attendance;  

SET @sql = CONCAT('SELECT v.vol_id  
                    , v.vol_giv_name  
                    , v.vol_fam_name, ', @sql, '   
                   FROM volunteer v  
                   LEFT JOIN volunteer_attendance AS va   
                    ON v.vol_id = va.vol_id  
                   GROUP BY v.vol_id');  

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

谢谢

0 个答案:

没有答案