Bil Jadual Data MySQL Tukar Penjelasan Terperinci
Langkah 1: Pilih lajur sasaran
Langkah 2: Lanjutkan jadual asas untuk menambah tambahan
Langkah 3: Jadual Sambungan Pakej dan Pengagregatan
Langkah 4: Mencantikkan (Pilihan)
Contoh
Pertimbangkan jadual asas berikut:Buat jadual perspektif
hostid | itemname | itemvalue |
---|---|---|
1 | A | 10 |
1 | B | 3 |
2 | A | 9 |
2 | C | 40 |
<code class="language-sql">-- 步骤 1:选择目标列 SELECT hostid, itemname, itemvalue FROM history; -- 步骤 2:扩展基础表添加额外列 CREATE VIEW history_extended AS SELECT history.*, CASE WHEN itemname = "A" THEN itemvalue END AS A, CASE WHEN itemname = "B" THEN itemvalue END AS B, CASE WHEN itemname = "C" THEN itemvalue END AS C FROM history; -- 步骤 3:分组和聚合扩展表 CREATE VIEW history_itemvalue_pivot AS SELECT hostid, SUM(A) AS A, SUM(B) AS B, SUM(C) AS C FROM history_extended GROUP BY hostid; -- 步骤 4:美化 CREATE VIEW history_itemvalue_pivot_pretty AS SELECT hostid, COALESCE(A, 0) AS A, COALESCE(B, 0) AS B, COALESCE(C, 0) AS C FROM history_itemvalue_pivot; -- 最终结果 SELECT * FROM history_itemvalue_pivot_pretty;</code>
Atas ialah kandungan terperinci Bagaimana untuk Pivot Baris ke Lajur dalam MySQL?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!