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

前端之家收集整理的这篇文章主要介绍了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

解决方法

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
原文链接:https://www.f2er.com/mssql/77591.html

猜你在找的MsSQL相关文章