mySQL pivot Table Data AS ROWS
To convert the given data into a pivot table format, where question answers are displayed as columns, the following query can be used:SELECT a.ID, a.user_id, A.job_id, max(c.question ='是這個嗎?'然後b.answer end) max(c.question ='或this的情況? max(c.question ='or that?'然後b.answer end)還是那個? ' 從結果a 內部加入答案b 在a.id上= b.fk_result_id 內在加入問題c 在b.fk_question_id = c.id上 a.id的組 a.user_id, a.job_id
在此查詢中,案例表達式用於檢查問題表的問題列,並從答案表返回相應的答案。然後,使用最大的聚集函數來找到每個問題的最大值,這表示為該問題提供的答案。動態互動
對於未知或大型語句的情況,可以使用下面的SQL語句生成以下代碼: 選擇 group_concat(不同 concat( 'max(c.question =''',情況 問題, ''然後b.answer end) concat(''',問題,''') ) )進入@sql 提問; set @sql = concat('select a.id, a.user_id, a.job_id,',@sql,' 從結果a 內部加入答案b 在a.id上= b.fk_result_id 內在加入問題c 在b.fk_question_id = c.id上 a.id的組 a.user_id, A.job_id'); 從@SQL準備STMT; 執行STMT; DealLocation準備STMT;
此代碼生成一個動態的SQL語句,可以處理任何數量的問題。它通過將每個問題的最大值串聯爲列名稱來動態構造選擇子句。SELECT a.ID, a.user_ID, a.job_id, MAX(CASE WHEN c.question = 'Is it this?' THEN b.answer END) 'Is it this?', MAX(CASE WHEN c.question = 'Or this?' THEN b.answer END) 'Or this?', MAX(CASE WHEN c.question = 'Or that? ' THEN b.answer END) 'Or that? ' FROM Results a INNER JOIN Answers b ON a.id = b.fk_result_id INNER JOIN Question c ON b.fk_question_id = c.ID GROUP BY a.ID, a.user_ID, a.job_id
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3