色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

mysql縱表轉橫表函數

林玟書2年前12瀏覽0評論

在實際的數據庫應用中,經常需要對數據進行轉換,把縱表轉換成橫表。MySQL提供了一些函數,方便進行這種轉換。下面介紹幾種常用的函數。

1. GROUP_CONCAT
語法:GROUP_CONCAT(expression)
功能:將同一組的多個值行轉化為一行,并用逗號分隔
示例:
SELECT GROUP_CONCAT(name) FROM student;
結果:
+--------------------------+
| GROUP_CONCAT(name) |
+--------------------------+
| Tom,Jack,Mary |
+--------------------------+
2. GROUP_CONCAT+CONCAT
語法:SELECT GROUP_CONCAT(CONCAT(col1,'-',col2,'-',col3) SEPARATOR ' ') AS columns FROM tablename;
功能:將多個列合并成一列,用分隔符進行分隔
示例:
SELECT GROUP_CONCAT(CONCAT(name,'-',age) SEPARATOR ' ') AS student_info FROM student;
結果:
+------------------------------+
| student_info |
+------------------------------+
| Tom-20,Jack-22,Mary-21 |
+------------------------------+
3. CASE+GROUP_CONCAT
語法:SELECT GROUP_CONCAT(CASE TYPE WHEN ‘A’ THEN VALUE END) AS A, GROUP_CONCAT(CASE TYPE WHEN ‘B’ THEN
VALUE END) AS B, GROUP_CONCAT(CASE TYPE WHEN ‘C’ THEN VALUE END) AS C FROM tablename GROUP BY NAME
功能:將原表的行列轉化成多行,每列數據分別生成一列,用于分析統計
示例:
SELECT name, GROUP_CONCAT(CASE course WHEN 'math' THEN score END) AS math, GROUP_CONCAT(CASE course WHEN
'english' THEN score END) AS english, GROUP_CONCAT(CASE course WHEN 'history' THEN score END) AS history FROM
score GROUP BY name;
結果:
+------+--------+---------+---------+
| name | math | english | history |
+------+--------+---------+---------|
| Tom | 80 | 85 | 70 |
| Jack | 90 | 78 | 80 |
| Mary | 75 | 88 | 87 |
+------+--------+---------+---------+
以上三種函數是常用的縱表轉橫表函數,在實際應用中,可以根據需求自行調整。