我從Cade Roux的出色答案開始,但將WITH ... AS()更改爲使用表變量,因爲我最終使用類似查詢的結果來進一步聚合fu nctions。
-- 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
光滑!! _________ – Haoest 2010-09-10 19:08:37