Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can SQL calculate aggregate functions across multiple tables?

Tags:

sql

Let's say I have two existing tables, "dogs" and "cats":

 dog_name | owner
 ---------+------
 Sparky   | Bob
 Rover    | Bob
 Snoopy   | Chuck
 Odie     | Jon

 cat_name | owner
 ---------+------
 Garfield | Jon
 Muffy    | Sam
 Stupid   | Bob

How do I write a query with this output?

 owner | num_dogs | num_cats
 ------+----------+---------
 Bob   |     2    |    1
 Chuck |     1    |    0
 Sam   |     0    |    1
 Jon   |     1    |    1
like image 577
mike Avatar asked Nov 25 '08 23:11

mike


People also ask

Why WHERE Cannot be used with aggregate functions?

We cannot use the WHERE clause with aggregate functions because it works for filtering individual rows. In contrast, HAVING can works with aggregate functions because it is used to filter groups.

Do aggregate functions apply to groups of rows?

In addition to providing information about an entire table, aggregate functions can be used on groups of rows. The GROUP BY clause arranges rows into groups, and aggregate functions return a single value for each group of rows.

Can aggregate functions be used without GROUP BY?

And data aggregation is impossible without GROUP BY! Therefore, it is important to master GROUP BY to easily perform all types of data transformations and aggregations. In SQL, GROUP BY is used for data aggregation, using aggregate functions.

How do I use multiple aggregate functions in SQL?

The first option is to combine two aggregate functions using a subquery. The subquery is a query within the main query. When creating reports, they are usually found in the SELECT , FROM , or WHERE clauses. In this example, I'll put the subquery in the FROM clause.


2 Answers

select owner, sum(num_dogs), sum(num_cats) from
  (select owner, 1 as num_dogs, 0 as num_cats from dogs
   union
   select owner, 0 as num_dogs, 1 as num_cats from cats)
group by owner
like image 114
Andru Luvisi Avatar answered Oct 06 '22 10:10

Andru Luvisi


I prefer this one:

select owner
     , count(dog_name) dogs
     , count(cat_name) cats
  from cats FULL OUTER JOIN dogs ON (cats.owner = dogs.owner)
like image 40
FerranB Avatar answered Oct 06 '22 11:10

FerranB