查询带有两个表的sql,并显示计数总数

时间:2014-02-18 22:52:54

标签: sql sqlite

我有一个名为“star”的表,有两列名人,电影和另一个名为“releases”的表,其中有两列名为album,album。我想创建一个查询,向我显示一个包含树新列的表:名人,专辑数量,电影数量。

所以我的想法是,我想要展示已经播放到电影中的名人(来自星表),还制作了一张专辑(来自发行表)以及低于电影和专辑的数量。

谢谢

3 个答案:

答案 0 :(得分:0)

我认为你的意思是“专辑数量”和“电影数量”。如果这是正确的,这应该有效:

select celeb,
       sum(case when num_type = 'movie' then num_recs else 0 end as num_movies,
       sum(case when num_type = 'album' then num_recs else 0 end as num_albums
  from (select celeb, count(*) as num_recs, 'movie' as num_type
          from star
         group by celeb
        union
        select celeb, count(*) as num_recs, 'album' as num_type
          from releases
         group by celeb) x
group by celeb

答案 1 :(得分:0)

也许这就是你要找的东西:

SELECT movie.celeb, movieCount, albumCount 
FROM 
  (SELECT celeb, count(1) movieCount 
   FROM star GROUP BY celeb) movie INNER JOIN
  (SELECT celeb, count(1) albumCount 
   FROM releases GROUP BY celeb) album ON movie.celeb=album.celeb

答案 2 :(得分:0)

select s.celeb, count(distinct movie), count(distinct album)
from star s join releases r on r.celeb = s.celeb
group by s.celeb