gpt4 book ai didi

SQL Select 语法解决方法

转载 作者:行者123 更新时间:2023-12-04 19:29:36 26 4
gpt4 key购买 nike

假设我有两个现有表,“狗”和“猫”:

 dog_name | owner ---------+------ Sparky   | Bob Rover    | Bob Snoopy   | Chuck Odie     | Jon cat_name | owner ---------+------ Garfield | Jon Muffy    | Sam Stupid   | Bob

How do I write a query with this output?

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

The answer I've got is the next query

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

但问题是sql不支持“select * from (select...)”查询类型

相反,在“from”之后必须有一个表名。

不幸的是我买不起临时 table 或 table 使用“select into”子句创建。我需要一些解决方法以这种方式形成嵌套 select 子句的建议解决方案。

你怎么看?

干杯

最佳答案

我的 SQL 可以,只需要为表命名...您使用的是什么数据库?

 select owner, sum(num_dogs), sum(num_cats) from
(select owner, 1 as num_dogs, 0 as num_cats from dogs
union all
select owner, 0 as num_dogs, 1 as num_cats from cats) as g
group by owner

关于SQL Select 语法解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/583793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com