2012-04-06 69 views
9

我知道如何在mysql中创建数据透视表(请参阅下面的代码示例),但如果数据透视表中的列数非常大,而且我不想输入2000左右的标记名? - 有没有办法让这个列表生成? 非常感谢提前。mysql中的数据透视表

drop table pivot; 
create table pivot SELECT time, 
     max(if(tagname = 'a', value, null)) AS 'a', 
     max(if(tagname = 'b', value, null)) AS 'b', 
     max(if(tagname = 'c', value, null)) AS 'c' 
    FROM test where tagname in ('a','b','c') 
GROUP BY time; 
select * from pivot; 
+3

外观在 本文。 http://buysql.com/mysql/14-how-to-automate-pivot-tables.html – GeoGo 2012-04-06 15:02:33

回答

1

你总是可以创建一个shell脚本,正是这么做:-)

#!/bin/sh 

mysql -BN test > /tmp/$$_tagnames.tmp <<SQL 
select distinct tagname from test; 
SQL 

cat > /tmp/$$_create_table.sql <<EOF 
drop table if exists pivot; 
create table pivot select 
EOF 

while read tag; do 
    echo "max(if(tagname = '$tag', value, null)) AS '$tag'," >> /tmp/$$_create_table.sql 
done < /tmp/$$_tagnames.tmp 

cat >> /tmp/$$_create_table.sql <<EOF 
time 
FROM test 
GROUP BY time; 
select * from pivot; 
EOF 

mysql -Bt test < /tmp/$$_create_table.sql 

rm /tmp/$$_create_table.sql 
rm /tmp/$$_tagnames.tmp 

数据:

mysql> select * from test; 
+---------+-------+---------------------+ 
| tagname | value | time    | 
+---------+-------+---------------------+ 
| a  | foo | 2012-12-21 00:00:01 | 
| b  | foo | 2012-04-27 00:00:01 | 
| c  | bar | 2012-03-27 00:00:01 | 
| d  | bar | 2012-12-21 00:00:01 | 
+---------+-------+---------------------+ 
4 rows in set (0.00 sec) 

脚本输出:

$ ./pivot.sh 
+------+------+------+------+---------------------+ 
| a | b | c | d | time    | 
+------+------+------+------+---------------------+ 
| NULL | NULL | bar | NULL | 2012-03-27 00:00:01 | 
| NULL | foo | NULL | NULL | 2012-04-27 00:00:01 | 
| foo | NULL | NULL | bar | 2012-12-21 00:00:01 | 
+------+------+------+------+---------------------+ 
+0

这是一个巧妙的shell脚本使用,这种模式也可以用于其他语言。 – 2012-05-02 11:04:02