简体   繁体   中英

Oracle SQL join three tables and group by column

I have three tables and I want a query te select teacher names and the number of classes each teacher has reserved.

teacher:

| idt | name |

class:

| idc | name |

reserve:

| idc | idt |

My query:

select
  t.name, count(distinct(r.idc))
  from
  teacher t
  join 
  reserve r
  on
  r.idt = t.idt
  join
  class c
  on
  c.idc = r.idc
  group by r.idc

When I run this I get the followin error: not a group by expression.

The group by clause needs to contain all non-aggregated columns from the select statement; in your case it should be t.name . Also, distinct is not a function but a keyword and should not have parentheses.

select
  t.name, 
  count(distinct r.idc) as number_of_classes
from
  teacher t
join 
  reserve r on r.idt = t.idt
join
  class c on c.idc = r.idc
group by 
  t.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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