Google這篇得到以下結果
基本上還是列出全部的column header(只是用sql的方式產生sum case when指令)
參考看看可不可用
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN exit_station = "', exit_station , '" THEN population ELSE 0 end) AS ' , '"' , exit_station , '"')
)
INTO @sql
FROM YourTable;
SET @sql = CONCAT('SELECT enter_station , ', @sql, '
FROM YourTable
GROUP BY enter_station');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
成功了,感謝大神,後來發現前面需要擴大字元限制,不然一直失敗,寫在下面提供給大家:
SET SESSION group_concat_max_len = 1000000;
另外,想詢問若要輸出成csv,要怎麼輸出呢?因為@sql算是一個暫存的檔(可能我理解錯誤),所以不確定要如何書寫?
因為我現在是寫這樣
SET @csv_export_command = CONCAT(
'SELECT * FROM (', @sql, ') AS result INTO OUTFILE "D:/MYSQL/MySQL_Data/Uploads/output.csv" FIELDS TERMINATED BY "," ENCLOSED BY '"''
);
PREPARE csv_stmt FROM @csv_export_command;
EXECUTE csv_stmt;
DEALLOCATE PREPARE stmt;
DEALLOCATE PREPARE csv_stmt;
但我不太知道如果同時要把欄位名輸出要怎麼改
建議使用一些線上產好語法的工具,這樣大神比較快可以處理,他們時間很寶貴。
我先建好給大神回答
資料表建立