SQL:在 select 列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中

SQL: is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

left join
     (
     SELECT my_number, MAX(id) as id
     FROM table1
     GROUP BY location 
     ) newNum
     on newNum.Part = c.OtherPart

left join table2 t2 on t2.id = newNum.id and t2.site = a.site

情况:我在 table1 中有数据字段(以及其他字段)my_number、位置和 ID。在 table2 中,我有数据字段(以及其他)id、站点、日期。我将这些加入到其他 views/tables(c 和 a)中,它们具有一些相同的数据字段和 my_numbers.

我的目标:每个 my_number 都有多个 ID,我希望每个站点的 ID 值最大。这就是我按站点分组的原因。 然后我需要根据id获取my_number的'date',因为第二个table不包含my_number,只是它的关联id。 共有 3 个站点,因此我需要每个站点的 3 个最大 id 值。然后我想得到这 3 个 id 值的 'date'

输出table例如:

a.num   a.site  a.date  c.OtherPart T2.date
15            TN    1.1.16        17    3.19.16
15            FL    2.21.16       17    4.22.16
15            TX    1.7.15        17    3.21.16

不确定您想对 sql 做什么,您应该只获取出现在 GROUP BY 中的列或聚合函数中的其他列,无论如何请尝试这样做;)

left join
     (
         SELECT my_number, id
         FROM table1 T1,
             (SELECT location, MAX(id) as id
             FROM table1
             GROUP BY location) TMP
         WHERE T1.id= TMP.id AND T1.location = TMP.location
     ) newNum
     on newNum.Part = c.OtherPart

left join table2 t2 on t2.id = newNum.id and t2.site = a.site

您也可以按照 sql 来修复此错误,但可能不是您想做的,

left join
     (
     SELECT location, MAX(id) as id
     FROM table1
     GROUP BY location 
     ) newNum
     on newNum.Part = c.OtherPart

left join table2 t2 on t2.id = newNum.id and t2.site = a.site

当您在 SQL 查询中放置类似 max(column) 的内容时,max 函数将对一组列的一组值进行操作。如果您使用分组依据定义查询,以便对结果进行分组,则每一列(除了您分组的那一列)都有多个值。

在您的例子中,location 有一个值(这是您分组的依据),但 my_numberid 有多个值。如果my_number是(1,2,3,4),id是(5,6,7,8),可以显示sum(my_number)或max(my_number)但是显然你不能在一行中显示 'number' my_number。这不是一个数字,而是一个列表。

这就是错误消息显示 "SQL: is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" 时的意思 如果您将列 my_column 放入聚合函数(如 sum),它将起作用,或者如果您添加将它添加到 group by 子句中它将起作用。