有子句时出错

Shi*_*ine 7 sql sql-server

select SUM (Bill) from ProductSaleReport group by PCI 
having MONTH(Date) between 1 and 3
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我找到问题.

我收到错误:

消息8121,级别16,状态1,行1
列'ProductSaleReport.Date'在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中.
消息8121,级别16,状态1,行1
列'ProductSaleReport.Date'在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中.

And*_*nko 12

MONTH(日期)不是您分组的列,因此它不会出现在having子句中.你可以这样做:

select SUM (Bill) 
from ProductSaleReport
where MONTH(Date) between 1 and 3
group by PCI 
Run Code Online (Sandbox Code Playgroud)

其他方式是

select SUM (Bill) 
from ProductSaleReport 
group by PCI, MONTH(Date) 
having MONTH(Date) between 1 and 3
Run Code Online (Sandbox Code Playgroud)

但请记住,您将获得按月和PCI分组的结果.

这里解释了WHERE和HAVING之间的区别:在where子句中使用'case expression column'


nik*_*trs 8

用于WHERE在分组前过滤

HAVING 用于在发生组后过滤数据

select SUM (Bill) -- comment: you need to add the PCI column since you use it in the group by right?
from ProductSaleReport 
WHERE MONTH(Date) between 1 and 3
group by PCI 
Run Code Online (Sandbox Code Playgroud)