Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey I have a problem I'm trying to do a select as seen below:
SQL
SELECT SUM(Invoice.TotalPrice) AS "Total", Customer.LastName, Customer.FirstName
FROM Invoice
INNER JOIN Customer
ON Invoice.CustomerID = Customer.CustomerID
WHERE DATEDIFF ( MONTH , Invoice.DateOrderPlaced , GETDATE() ) > 3 AND "Total"  > 20000
GROUP BY Invoice.CustomerID, Customer.LastName, Customer.FirstName;

The problem i've got is the:
3 AND "Total"  > 20000

I want it to mean the total of price where customer ID is the same. Anyone got any suggestions?
Posted
Updated 15-Dec-11 0:43am
v2

1 solution

Just use the summary function in a HAVING clause

SQL
SELECT SUM(Invoice.TotalPrice) AS "Total", Customer.LastName, Customer.FirstName
FROM Invoice
INNER JOIN Customer
ON Invoice.CustomerID = Customer.CustomerID
WHERE DATEDIFF ( MONTH , Invoice.DateOrderPlaced , GETDATE() ) > 3
GROUP BY Invoice.CustomerID, Customer.LastName, Customer.FirstName
HAVING SUM(Invoice.TotalPrice) > 20000
 
Share this answer
 
v2
Comments
WurmInfinity 15-Dec-11 6:54am    
Thank you kindly.
Sara Dark 15-Dec-11 7:59am    
thank you your answer was enough i know the difference now :)
Sara Dark 15-Dec-11 7:53am    
please can u explain briefly y "WHERE DATEDIFF ( MONTH , Invoice.DateOrderPlaced , GETDATE() ) > 3" wasn't added in the query with having
HAVING (SUM(Invoice.TotalPrice) > 20000 AND DATEDIFF ( MONTH , Invoice.DateOrderPlaced , GETDATE() ) > 3).
Im no expert i just want to know what difference does it make?
Dylan Morley 15-Dec-11 7:57am    
Have a look at this article which explains a few things...

http://www.codeproject.com/KB/database/Where_Vs_Having_Clause.aspx

"Here's the rule. If a condition refers to an aggregate function, put that condition in the HAVING clause. Otherwise, use the WHERE clause. "

In the above query, the DATEDIFF statement was saying which records we wanted in the results but no aggregation took place, so we can use the WHERE clause for this.

However, tTotalPrice requires aggregation, so it has to happen in the HAVING clause.

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