Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL error: misuse of aggregate

Tags:

sql

sqlite

SQLite version 3.4.0 What's wrong with aggregate functions? Additionally, I suspect that ORDER BY won't work as well. How to rewrite this?

sqlite> SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2    ...> FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2    ...> WHERE p1.id = i1.PDB_first_id    ...> AND p2.id = i2.PDB_second_id    ...> AND i1.id = i2.id    ...> AND d1>100    ...> AND d2>100    ...> ORDER BY d1, d2; SQL error: misuse of aggregate:  sqlite> 
like image 993
Piotr Byzia Avatar asked Mar 15 '09 16:03

Piotr Byzia


People also ask

Does SQL support aggregating data?

An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function ignores NULL values when it performs the calculation, except for the count function.

What is SQL Agregation?

SQL aggregation is the task of collecting a set of values to return a single value. It is done with the help of aggregate functions, such as SUM, COUNT, and AVG. For example, in a database of products, you might want to calculate the average price of the whole inventory.


1 Answers

When using an aggregate function (sum / count / ... ), you also have to make use of the GROUP BY clause.

Next to that, when you want to filter on the result of an aggregate , you cannot do that in the WHERE clause, but you have to do that in the HAVING clause.

SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2     FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2     WHERE p1.id = i1.PDB_first_id     AND p2.id = i2.PDB_second_id     AND i1.id = i2.id GROUP BY p1.domain_Id, p2.domain_Id HAVING d1 > 100 AND d2 > 100 ORDER BY d1, d2; 
like image 179
Frederik Gheysels Avatar answered Sep 20 '22 16:09

Frederik Gheysels