我希望在我的SQL查询中有一个switch case,这样当group by不对任何元素进行分组时我不想聚合,否则我想要。这可能。
我的查询是这样的:
select count(1),AVG(student_mark) ,case when Count(1)=1 then student_subjectid else null end from Students
group by student_id
我收到此错误列'student_subjectid'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
提前致谢..
答案 0 :(得分:2)
SELECT
student_id,
COUNT(*) AS MarkCount,
AVG(student_mark) AS student_mark,
CASE COUNT(*) WHEN 1 THEN MIN(student_subjectid) END AS student_subjectid
FROM Students
GROUP BY student_id
答案 1 :(得分:1)
为什么世界会让你复杂化?
select count(1), AVG(Student_mark) Student_mark
from Students
group by student_id
如果只有一个student_mark,它也是SUM,AVG,MIN和MAX - 所以只需继续使用聚合!
<小时/>
最符合您要求的数据集通常不会有意义。实现这一目标的方法是合并(联合)两个不同的结果
select
numRecords,
Student_mark,
case when numRecords = 1 then student_subjectid end # else is implicitly NULL
from
(
select
count(1) AS numRecords,
AVG(Student_mark) Student_mark,
min(student_subjectid) as student_subjectid
from Students
group by student_id
) x