简体   繁体   English

将聚合函数应用于多个表的计数/分组

[英]Apply aggregates function on count / group by on multiple tables

I Have 2 tables 我有2张桌子

table1 (sailors): table1(水手):

id_sailor   name 
1       Barondeau   
2       Vighetti    

table2 (voyages): 表2(航程):

id_ voyage     boat       id_sailor
1                Juliette         1
2                Juliette         1
3               La belle          2
4               La Belle          1

How can I make this new table : 我如何制作这张新桌子:

n is the number of voyages for a sailor on a specific boat – n是特定船上水手的航行次数–

   boat     name      n     
   Juliette Barondeau 2
   La Belle Barondeau 1
   La Belle Vighetti  1

What I tried : 我试过了

  select "table2"."boat", "table1"."name", count("table2"."boat" ) as "n"
  from "table1", "table2" 
  where "table1"."id_sailor" = "table2"."id_sailor"
  group by "table2"."name"
  ;

In hsqldb 1.8, I have this error "Not in aggregate function or group by clause : 1b6128f..." 在hsqldb 1.8中,出现此错误“不在聚合函数或group by子句中:1b6128f ...”

You need to add group by "table2"."boat" in your GROUP BY clause remaining looks fine. 您需要在GROUP BY子句中添加group by "table2"."boat" ,看起来还不错。

 group by "table2"."boat","table2"."name"

instead of 代替

group by "table2"."name"

Appears to simple "group by" based query 出现简单的基于“分组依据”的查询

select
      v.boat, s.name, count(*) n
from voyages v
innner join sailors s on v.id_sailor = s.id_sailor   
group by
      v.boat, s.name

The important point to note here is that ALL selected columns NOT USING aggregate functions {such as COUNT( )}* should be listed in the group by clause. 这里要注意的重要一点是,所有不使用聚合函数的选定列{如COUNT( )} *都应在group by子句中列出。

just need to add group by table2.boat. 只需添加由table2.boat组。

select table2.boat, table1.name, count(table2.boat) as n
from table1, table2 
where table1.id_sailor = table2.id_sailor
group by table1.name , table2.boat;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM