【问题标题】:Switch case in aggregate query在聚合查询中切换大小写
【发布时间】:2011-04-18 03:07:13
【问题描述】:

我想在我的 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 子句中。

提前谢谢..

【问题讨论】:

  • 感谢您的编辑.. :)
  • 编辑源后错误消息变得无关紧要。您应该在更改后的代码中添加EDIT 注释。否则你应该删除或替换原来的错误信息,因为它现在很混乱。
  • 你在说什么?我自己编辑了源代码。
  • 你的意思是说我应该保留我的问题,并将更改查询添加为编辑..
  • 我说的是您在问题中包含的此错误消息:Column 'Student_mark' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 我知道它与您的查询的先前版本有关。您更新的脚本不会产生此错误。

标签: sql tsql aggregate


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    你到底为什么要把它复杂化?

    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
    

    【讨论】:

    • 这只是一个例子.. 假设我想在这种情况下选择那个学生的一些其他属性,比如 subjectid 那么?
    • 虽然这个解决方案是最简单的方法,我想到了这一点..对于像这样的小查询很好..但我的实际查询涉及很多连接,我不能让它运行两次..任何其他想法..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2020-07-19
    相关资源
    最近更新 更多