简体   繁体   中英

Count of number occurrences in a column

I have the following table

actor_id    movie_id
---------------------
   1           20
   2           10
   3            8
   4            6
   1           21

I need the following output

actor_id    movie_count
-----------------------
   1           2
   2           1
   3           1
   4           1

You need to "aggregate". To count how many movies there are for each actor you can do:

select
  actor_id,
  count(*) as movie_count
from t
group by actor_id

Now, if you need to count how many different movies are for each actor, you can do:

select
  actor_id,
  count(distinct movie_id) as movie_count
from t
group by actor_id

You should ask another question if you change the expected result. Anyway, here's the augmented query that adds the first name of the actor:

select
  c.*, 
  a.first_name, 
  a.id
from (
  select
    actor_id,
    count(*) as movie_count
  from t
  group by actor_id
) c
join actor a on a.actor_id = c.actor_id

You need to count all the rows grouped by actor_id. You can use below query

select actor_id,count(*) Movie_count from tableName
group by actor_id
order by actor_id

You can use group by to aggregate

select actor_id,count(*) as movie_count
from table_name
group by actor_id

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