sql语句学习笔记(10)-group by(因为该列没有包含在聚合函数或 GROUP BY 子句中。聚合函数不能出现在where中)

捐款表tb_donation的结构如下:

id          name          direction         amount

1            a                  地震                200

2            a                  旱灾                400

3            a                  地震                400

5            b                  地震                200

9            b                  旱灾                200

11          c                   地震                200

...         ...                  ...                    ...

...         ...                  ...                    ...

...         ...                  ...                    ...

 

统计捐款超过2次的人:

select * from tb_donation,sum(amount)

group by name

having count(*)>1

这样会报错误:因为该列没有包含在聚合函数或 GROUP BY 子句中.

原因在于:group by后要求出现select子项中所有的非聚合函数列,上述语句中的*包含了多列,但只有name在group by中出现,所以会报错。

结论:使用group by时,select的子项必须在group by中出现或是出现在聚合函数中。

上述语句应该写成:

select name  from tb_donation,sum(amount)

group by name

having count(*)>1

也不要写成了

select name  from tb_donation,sum(amount)

where count(*)>1

group by name

 

where条件时最初始的帅选条件,不能出现聚合函数

 

你可能感兴趣的:(SQL,SERVER,sql,c)