为什么我的查询在添加SUM函数时失败?

时间:2014-11-14 18:03:23

标签: sql sql-server sql-server-2008

以下查询按预期执行,在给定要查询的字段的情况下给出预期输出

SELECT 1 as SEQ, TERM_DESC as TERM, PRIMARY_COLLEGE_DESC as COLLEGE, LEVEL_GROUPING_CODE as     LEVEL_CODE, LEVEL_GROUPING_DESC as LEVEL_DESC
FROM SECopy as SE

但是,当我在一个字段上添加函数SUM()时,我收到关于TERM_DESC的以下错误,该错误甚至与使用SUM()函数的ID_COUNT无关。

SELECT 1 as SEQ, TERM_DESC as TERM, PRIMARY_COLLEGE_DESC as COLLEGE, LEVEL_GROUPING_CODE as     LEVEL_CODE, LEVEL_GROUPING_DESC as LEVEL_DESC, SUM(ID_COUNT) as HEADCOUNT
from SECopy as se 

我收到以下错误:

Column 'Student_Enrollment_copy.TERM_DESC' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

为什么只在添加SUM()函数后才会失败?

4 个答案:

答案 0 :(得分:2)

  1. 不需要表的别名
  2. 您应该使用Group BY子句中除Aggregate Function之外的所有列
  3. SELECT 1 as SEQ, 
    TERM_DESC as TERM, 
    PRIMARY_COLLEGE_DESC as COLLEGE, 
    LEVEL_GROUPING_CODE as     LEVEL_CODE,
    SUM(ID_COUNT) as HEADCOUNT
    from SECopy
    GROUP BY TERM_DESC,PRIMARY_COLLEGE_DESC,LEVEL_GROUPING_CODE
    

答案 1 :(得分:1)

您需要粘贴SELECT语句中的任何字段,但不要将SUM(),AVG(),MIN()等聚合到GROUP BY子句中:< / p>

SELECT 
    1 AS SEQ,
    TERM_DESC AS TERM,
    PRIMARY_COLLEGE_DESC AS COLLEGE,
    LEVEL_GROUPING_CODE AS LEVEL_CODE,
    LEVEL_GROUPING_DESC AS LEVEL_DESC,
    SUM(ID_COUNT) AS HEADCOUNT
FROM SECopy AS se
GROUP BY 
    TERM_DESC, PRIMARY_COLLECT_DESC,LEVEL_GROUPING_CODE,LEVEL_GROUPING_DESC

答案 2 :(得分:1)

您需要为查询添加分组条件。

在SQL server(以及许多其他SQL RDBMS)中,聚合函数需要分组列的定义:

select ...., sum(...) ...  -- Fields, expresions and (aggregate) functions
from your_table -- and / or data sources
-- any where conditions
group by ... --- Grouping criteria

答案 3 :(得分:0)

根据您的实际需要,您可能正在寻找

SELECT
  1 as SEQ
  , TERM_DESC as TERM
  , PRIMARY_COLLEGE_DESC as COLLEGE
  , LEVEL_GROUPING_CODE as LEVEL_CODE
  , LEVEL_GROUPING_DESC as LEVEL_DESC
  , (SELECT SUM(ID_COUNT) FROM SECOPY) as HEADCOUNT
from SECopy