[英]SQL get avg of column for id 1, grouped by values in the same column for id 2
我表中的同一列需要用於平均和分組依據。 問題是在實現每個 function 時,id 是不同的。
我的作業問題是“你的年齡是多少”和“你的性別是什么”。
我找到了前 7 位性別,它們是: 'Male'
、 'Female'
、 'male'
、 'female'
、 '-1'
、 'Nonbinary'
、 'non-binary'
。
AnswerText 包含每個問題的答案。 我想獲取列表中每個性別類別的平均年齡。 我這樣做了:
SELECT AVG(AnswerText), Gender
FROM
(
SELECT AnswerText as Gender
FROM Answer
WHERE Answer.QuestionID = 2
AND Gender IN ('Male', 'Female', 'male', 'female', '-1', 'Nonbinary', 'non-binary')
)
WHERE Answer.QuestionID = 1
GROUP BY Gender
這是拋出錯誤no such column: AnswerText
。
我如何實現這一目標? 解決方案可以在 MySQL 或 SQLite 中。
我想獲取列表中每個性別類別的平均年齡。
這是一個自連接:
select a2.answertext as gender, avg(a1.answertext * 1.0) as avg_age
from answer a1
inner join answer a2 on a2.userid = a1.userid
where a1.questionid = 1 and a2.questionid = 2
group by a2.answertext
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.