Advertisement

07.24.2008 at 12:37PM PDT, ID: 23593504
[x]
Attachment Details

Another aggregate function in the where clause

Asked by YZlat in SQL Query Syntax, MS SQL Server

I have 2 tables:

Table1
________
Id
Name
Desc
Notes

Table2
_______
Id
Table1ID
Total
Avail
Details
Misc

Table2 can contain multiple records for each Name from Table1.

I need to retrieve the count of all recods in Table1 where sum of Avail is less than 10% of sum of the Total in Table2

I have the following query:

SELECT COUNT(a.Id)
FROM Table1 a
LEFT OUTER JOIN Table2 b ON a.Id = b.Table1ID
WHERE not b.Total is null
AND SUM(b.Avail) < (SUM(b.Total)/10)

but it gives me an error "An aggregate may not appear in the WHERE clause..."
I tried


SELECT COUNT(a.Id)
FROM Table1 a
LEFT OUTER JOIN Table2 b ON a.Id = b.Table1ID
WHERE not b.Total is null
HAVING SUM(b.Avail) < (SUM(b.Total)/10)


but also got an error about Arithmetic overflow

How can I accomplish my task in one query?
Start Free Trial
[+][-]07.24.2008 at 12:58PM PDT, ID: 22082909

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: SQL Query Syntax, MS SQL Server
Sign Up Now!
Solution Provided By: DBoyes
Participating Experts: 2
Solution Grade: B
 
 
[+][-]07.24.2008 at 01:14PM PDT, ID: 22083089

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]07.24.2008 at 01:20PM PDT, ID: 22083156

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]07.24.2008 at 01:23PM PDT, ID: 22083187

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628