Can SQL calculate aggregate functions across multiple tables?

后端 未结 5 1769
北恋
北恋 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题