需要帮助以两个不同的宠物总和创建视图

时间:2018-11-15 21:24:34

标签: tsql join count sum

我正在尝试创建一个视图,该视图创建一个表,该表给出了狗的总和和猫的总和。 这就是我目前所拥有的。但是我不确定如何进入视图格式。

select count(PetType) as [Amount of Dogs]
from Pets
where pettype = 'dog'

select count(PetType) as [Amount of Cats]
from Pets
where PetType = 'cat'

谢谢您的帮助。

2 个答案:

答案 0 :(得分:0)

CREATE VIEW v AS
SELECT * FROM
(select count(PetType) as [Amount of Dogs] from Pets where pettype = 'dog') d
CROSS JOIN
(select count(PetType) as [Amount of Cats] from Pets where PetType = 'cat') c

答案 1 :(得分:0)

仅使用条件聚合:

select sum(case when PetType = 'dog' then 1 else 0 end) as num_dogs,
       sum(case when PetType = 'cat' then 1 else 0 end) as num_cats
from Pets;
相关问题