Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with having clause

Tags:

sql

sql-server

select SUM (Bill) from ProductSaleReport group by PCI 
having MONTH(Date) between 1 and 3

Could any one please help me finding the issue.?

I am getting the errors:

Msg 8121, Level 16, State 1, Line 1
Column 'ProductSaleReport.Date' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8121, Level 16, State 1, Line 1
Column 'ProductSaleReport.Date' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

like image 486
Shine Avatar asked Jul 27 '11 06:07

Shine


1 Answers

MONTH(Date) is not a column you're grouped by, so it can't appear in having clause. You can do like that:

select SUM (Bill) 
from ProductSaleReport
where MONTH(Date) between 1 and 3
group by PCI 

Other way is

select SUM (Bill) 
from ProductSaleReport 
group by PCI, MONTH(Date) 
having MONTH(Date) between 1 and 3

but keep in mind that you will get result grouped by month as well as by PCI.

The difference between WHERE and HAVING explained here: Using 'case expression column' in where clause

like image 155
Andrei Petrenko Avatar answered Oct 15 '22 04:10

Andrei Petrenko