Click here to Skip to main content
15,895,848 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a 2 tables the tblPayment that have a column of 'Payment'; and the tblMonthlyReports having a column of 'Gross'.
I am trying to sum all the payments in column Payment in tblPayment the result will be display in Gross column in tblMonthlyReports. But I got an error saying
Msg 147, Level 15, State 1, Line 12
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.


What I have tried:

SQL
USE [NEWCMO]
GO

SELECT [Months]
      ,[Patient/Month]
      ,[Gross]
      ,[Abatement]
      ,[Net]
  FROM [dbo].[tblMonthlyReports]
GO

SELECT Payment FROM tblPayment WHERE Payment=(SELECT SUM(Payment) AS Gross FROM tblMonthlyReports);
Posted
Updated 13-Feb-17 7:02am
v2

1 solution

If you're using aggregate functions you always have to add a GROUP BY clause to tell the SQL engine by which column value it should aggregate (group) the data. The HAVING clause may be used to filter the resulting rows but this is not required, if not needed. Your query should look something like:

SQL
SELECT Months
     , SUM(Payment) AS Gross
  FROM tblMonthlyReports
GROUP BY Months
WHERE Months IS NOT NULL
  AND Payment IS NOT NULL


THis will result in several records each showing the sum of payments for the belonging month (one record for each month that occurs in tblMonthlyReports).

...and don't forget the WHERE clause, otherwise the aggreation may stop at the first NULL value which will lead into incorrect results!
 
Share this answer
 
Comments
Richard Deeming 13-Feb-17 16:28pm    
You can't put the WHERE clause after the GROUP BY clause. :)
NightWizzard 14-Feb-17 8:24am    
Oops...you're right! Typed it quick and dirty :O)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900