【问题标题】:Add new column to a table with a value group by value将新列添加到具有按值分组的表中
【发布时间】:2022-10-06 20:16:58
【问题描述】:

我有一个马戏团表如下

circus_id circus_date circus_show_price
1 09-12-2020 78
2 12-01-2021 82

和一张票表如下

ticket_id circus_id ticket_category
1 1 Adult
2 1 Student
3 1 Children
4 2 Adult
5 2 Children
6 2 Adult

我想通过添加一个名为 ticket_sold 的新列来更改马戏团表,并且值应如下所示

circus_id circus_date circus_show_price ticket_sold
1 09-12-2020 78 3
2 12-01-2021 82 3

这是我尝试过的

 alter table circus add ticket_sold numeric(3) default 0;
 update circus set ticket_sold = (select count(ticket_id) from ticket group by circus_id);

它给了我一个错误说

 single-row subquery returns more than one row

    标签: sql oracle group-by sql-update alter-table


    【解决方案1】:

    这不是您需要的 group by 子句,因为查询会返回每个马戏团的门票数量,但是 - 然后您会得到与 ticket 表中的 circus_ids 一样多的行。相反,将子查询关联到主表:

    update circus c set 
      c.ticket_sold = (select count(t.ticket_id) 
                       from ticket t
                       where t.circus_id = c.circus_id
                      );
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2022-12-13
      相关资源
      最近更新 更多