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

Putar tabel dan tampilkan n deret waktu yang dipesan

Coba ini:

SELECT r.id,
       r.`date`,
       GROUP_CONCAT(IF(r.device_id = 1,r.`VALUE`,NULL)) AS device_id_1,
       GROUP_CONCAT(IF(r.device_id = 2,r.`VALUE`,NULL)) AS device_id_2
FROM readings r
GROUP BY r.`DATE`
ORDER BY r.`DATE` ASC;

+----+---------------------+-------------+-------------+
| id | date                | device_id_1 | device_id_2 |
+----+---------------------+-------------+-------------+
|  1 | 2015-10-01 10:00:00 | 2           | 0.5         |
|  3 | 2015-10-01 10:01:00 | 3.1         | 7.5         |
+----+---------------------+-------------+-------------+
2 rows in set (0.00 sec)

Dan di sini Versi untuk device_id dinamis

SELECT  group_concat( 
    "GROUP_CONCAT(IF(device_id = ",
    device_id,",`value`,NULL)) AS device_id_",
    device_id
    SEPARATOR ',\n') INTO @sql_mid
FROM (SELECT DISTINCT device_id FROM readings ORDER BY device_id) AS r
ORDER BY device_id;

SELECT CONCAT("SELECT id, `date`, ", @sql_mid, " FROM readings GROUP BY `DATE` ORDER BY `DATE` ASC") INTO @sql;

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

Ini menghasilkan semua Kolom

+----+---------------------+-------------+-------------+-------------+
| id | date                | device_id_1 | device_id_2 | device_id_3 |
+----+---------------------+-------------+-------------+-------------+
|  1 | 2015-10-01 10:00:00 | 2           | 0.5         | NULL        |
|  3 | 2015-10-01 10:01:00 | 3.1         | 7.5         | NULL        |
|  5 | 2015-10-01 10:11:00 | NULL        | NULL        | 9.9         |
+----+---------------------+-------------+-------------+-------------+
3 rows in set (0.00 sec)



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. link validasi via email

  2. Bagaimana Fungsi REGEXP_SUBSTR() Bekerja di MySQL

  3. MySQL 5.5.9 dan kesalahan pembuatan tabel Hibernate pada TYPE

  4. Aktivitas terbaru pengguna - PHP MySQL

  5. sql bergabung sebagai diagram venn