[英]MySQL CROSSTAB or PIVOT Query
我有一個表格,其中分數列為1,0,結果為NA。 隨着針對這三個答案提交的分數越來越多,表格中的數據將繼續增長。
|id | username | answer1 | answer2 | answer3 |
--------------------------------------------
| 1 | John | 1 | 0 | 1 |
| 2 | Mike | NA | 1 | 1 |
| 3 | Jill | 1 | NA | 0 |
| 4 | Mary | 1 | 1 | 1 |
我正在嘗試創建一個選擇查詢,該查詢將顯示上表中列出的結果(總計1將總計1,總計2將總計所有O,總計將總計所有NA)。 我正在使用MySQL數據庫。
|questions | total_1 | total_0 |total_NA|
----------------------------------------
| answer1 | 3 | 0 | 1 |
| answer2 | 2 | 1 | 1 |
| answer3 | 3 | 0 | 0 |
簡單的答案,但我剛喝了一杯咖啡...
select 'answer1' as questions,
sum(case when answer1 = 1 then 1 end) as total_1,
sum(case when answer1 = 0 then 1 end) as total_0,
sum(case when answer1 = NA then 1 end) as total_NA
from tablename
UNION ALL
select 'answer2' as questions,
sum(case when answer2 = 1 then 1 end) as total_1,
sum(case when answer2 = 0 then 1 end) as total_0,
sum(case when answer2 = NA then 1 end) as total_NA
from tablename
etc...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.