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

MySQL, beberapa baris untuk memisahkan bidang

Anda baru saja melewatkan grup :)

SELECT PartNumber,
  MAX(IF (Priority = 0, SupName, NULL)) AS Sup1,
  MAX(IF (Priority = 1, SupName, NULL)) AS Sup2,
  MAX(IF (Priority = 2, SupName, NULL)) AS Sup3
FROM SupXref
GROUP BY PartNumber

Sunting:

Setelah bermain sebentar, saya pikir saya mendapatkan solusi pertama yang Anda cari. Cobalah :)

SELECT partnumber,
  COALESCE(Sup1, COALESCE(Sup2, Sup3)) AS Supp1,
  IF (Sup1 IS NULL, IF (Sup2 IS NULL, NULL, Sup3), COALESCE(Sup2, Sup3)) AS Supp2,
  IF (Sup1 IS NULL, NULL, IF (Sup2 IS NULL, NULL, Sup3)) AS Supp3
FROM (
  SELECT PartNumber,
    MAX(IF (Priority = 0, SupName, NULL)) AS Sup1,
    MAX(IF (Priority = 1, SupName, NULL)) AS Sup2,
    MAX(IF (Priority = 2, SupName, NULL)) AS Sup3
  FROM SupXref
  GROUP BY PartNumber
) AS S

Untuk tabel berikut:

+------------+----------+---------+
| PARTNUMBER | PRIORITY | SUPNAME |
+------------+----------+---------+
| a1         |        2 | Three   |
| a2         |        1 | Two     |
| a3         |        2 | Three   |
| a3         |        1 | Two     |
| a4         |        0 | One     |
| a5         |        0 | One     |
| a5         |        2 | Three   |
| a6         |        0 | One     |
| a6         |        1 | Two     |
| a7         |        0 | One     |
| a7         |        1 | Two     |
| a7         |        2 | Three   |
+------------+----------+---------+

Data berubah menjadi ini:

+------------+------+------+-------+
| PARTNUMBER | SUP1 | SUP2 | SUP3  |
+------------+------+------+-------+
| a1         |      |      | Three |
| a2         |      | Two  |       |
| a3         |      | Two  | Three |
| a4         | One  |      |       |
| a5         | One  |      | Three |
| a6         | One  | Two  |       |
| a7         | One  | Two  | Three |
+------------+------+------+-------+

Dan akhirnya menjadi ini:

+------------+-------+-------+-------+
| PARTNUMBER | SUPP1 | SUPP2 | SUPP3 |
+------------+-------+-------+-------+
| a1         | Three |       |       |
| a2         | Two   |       |       |
| a3         | Two   | Three |       |
| a4         | One   |       |       |
| a5         | One   | Three |       |
| a6         | One   | Two   |       |
| a7         | One   | Two   | Three |
+------------+-------+-------+-------+



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. PHP, PDO, MySQL, Pemberitahuan:Mencoba mendapatkan properti non-objek

  2. Masalah koneksi MySQLdb

  3. Apakah tabel MySQL memerlukan ID?

  4. PHP - MYSQL - server basis data uji

  5. MYSQL:Tabel Nomor Urutan