简体   繁体   English

SQL 获取 id 1 列的平均值,按 id 2 同一列中的值分组

[英]SQL get avg of column for id 1, grouped by values in the same column for id 2

The same column in my table needs to be used for Averaging and Grouping By.我表中的同一列需要用于平均和分组依据。 The catch is that the id is different when implementing each function.问题是在实现每个 function 时,id 是不同的。

答案表

My assignment questions are "What is your age" and "What is your gender".我的作业问题是“你的年龄是多少”和“你的性别是什么”。

I found the top 7 genders, these are: 'Male' , 'Female' , 'male' , 'female' , '-1' , 'Nonbinary' , 'non-binary' .我找到了前 7 位性别,它们是: 'Male''Female''male''female''-1''Nonbinary''non-binary'

AnswerText contains the answers for each question. AnswerText 包含每个问题的答案。 I want to get the Average age for each gender category in the list.我想获取列表中每个性别类别的平均年龄。 I have done this:我这样做了:

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

This is throwing error no such column: AnswerText .这是抛出错误no such column: AnswerText

How do I achieve this?我如何实现这一目标? The solution can either be in MySQL or SQLite.解决方案可以在 MySQL 或 SQLite 中。

I want to get the Average age for each gender category in the list.我想获取列表中每个性别类别的平均年龄。

That's a self-join:这是一个自连接:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM