【问题标题】:Need help creating a view with two different pet sums需要帮助创建具有两个不同宠物总和的视图
【发布时间】:2019-04-19 01:35:18
【问题描述】:

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

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

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

感谢您的帮助。

【问题讨论】:

    标签: tsql join count sum


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      只需使用条件聚合:

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-26
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        • 2020-03-06
        相关资源
        最近更新 更多