Can SQL calculate aggregate functions across multiple tables?

后端 未结 5 1735
北恋
北恋 2021-01-05 01:14

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

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


        
相关标签:
5条回答
  • 2021-01-05 01:53

    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)
    
    0 讨论(0)
  • 2021-01-05 01:56

    If your database can handle it, I'd double down on FerranB's solution and write a geeky NATURAL FULL JOIN solution. I mean, when was the last time you got the chance to do so?

    SELECT owner, COUNT(dog_name), COUNT(cat_name)
    FROM cats 
    NATURAL FULL JOIN dogs
    GROUP BY owner
    
    0 讨论(0)
  • 2021-01-05 02:01
    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
    
    0 讨论(0)
  • 2021-01-05 02:01

    In T-SQL for SQL Server 2005 (replace the CTE with an inline subquery if not):

    WITH ownership AS (
        SELECT owner, COUNT(dog_name) AS num_dogs, 0 AS num_cats -- counts all non-NULL dog_name
        FROM dogs
        GROUP BY owner
    
        UNION
    
        SELECT owner, 0 AS num_dogs, COUNT(cat_name) as num_cats -- counts all non-NULL cat_name
        FROM cats
        GROUP BY owner
    )
    SELECT ownership.owner
        ,SUM(ownership.num_dogs) AS num_dogs
        ,SUM(ownership.num_cats) as num_cats
    FROM ownership
    GROUP BY ownership.owner
    
    0 讨论(0)
  • 2021-01-05 02:01

    I started with Cade Roux's excellent answer, but changed the WITH...AS () to use a table variable, as I am ended up using the results from a similar query for further aggregate functions.

    -- Table variable declaration
    DECLARE @RainingCatsDogs TABLE
    (
        Owner nvarchar(255),
        num_cats int,
        num_dogs int
    )
    
    -- Populate the table variable with data from the union of the two SELECT statements
    INSERT INTO @RainingCatsDogs
    
    -- Get the count of doggies
    SELECT 
        owner, COUNT(dog_name) AS num_dogs, 0 AS num_cats
    FROM 
        dogs
    GROUP BY 
        owner
    
    -- join the results from the two SELECT statements
    UNION
    
    -- Get the count of kittehs
    SELECT 
        owner, 0 AS num_dogs, COUNT(cat_name) as num_cats
    FROM 
        cats
    GROUP BY 
        owner
    
    -- From the table variable, you can calculate the summed results
    SELECT
        owner,
        SUM(num_dogs),
        SUM(num_cats)
    FROM 
        @RainingCatsDogs
    
    0 讨论(0)
提交回复
热议问题