Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

tabel pivot di mysql

Anda selalu dapat membuat skrip shell yang melakukan hal itu :-)

#!/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

Data:

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)

Keluaran skrip:

$ ./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 |
+------+------+------+------+---------------------+



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Pernyataan Kasus di ARel

  2. mysql (hampir) menyelesaikan audit

  3. dbWriteTable(..., append =T) ditimpa dalam R

  4. Cara Membuat Database di MySQL Workbench menggunakan GUI

  5. JPA di Java SE:Objek:[dilindungi email] bukan tipe entitas yang dikenal