SQL可以跨多个表计算聚合函数吗?

时间:2008-11-25 23:30:54

标签: sql

假设我有两个现有的桌子,“狗”和“猫”:

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

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

如何使用此输出编写查询?

 owner | num_dogs | num_cats
 ------+----------+---------
 Bob   |     2    |    1
 Chuck |     1    |    0
 Sam   |     0    |    1
 Jon   |     1    |    1

5 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:5)

我更喜欢这个:

select owner
     , count(dog_name) dogs
     , count(cat_name) cats
  from cats FULL OUTER JOIN dogs ON (cats.owner = dogs.owner)

答案 2 :(得分:2)

在SQL Server 2005的T-SQL中(如果没有,则用内联子查询替换CT​​E):

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

答案 3 :(得分:1)

我从Cade Roux的优秀答案开始,但更改了WITH ... AS()以使用表变量,因为我最终使用类似查询的结果来获得更多的聚合函数。

-- 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

答案 4 :(得分:1)

如果您的数据库可以处理它,我会加倍努力FerranB's solution,并写一个令人讨厌的NATURAL FULL JOIN解决方案。我的意思是,您最后一次有机会这样做是什么时候?

SELECT owner, COUNT(dog_name), COUNT(cat_name)
FROM cats 
NATURAL FULL JOIN dogs
GROUP BY owner