【问题标题】:Struggling with subquery & joins挣扎于子查询和连接
【发布时间】:2021-07-28 16:07:41
【问题描述】:

我正在为我的数据类处理一个问题集,并且不断收到“缺少表达式”错误代码。这是我写的:

select c.numbkids "Number of Kids",
       (select avg(r.rating)
        from netflix.ratings100 r join netflix.movies_genres m on r.movieid = m.movieid
        where m.genrecode like 'ACT'),
       (select avg(r.rating)
        from netflix.ratings100 r join netflix.movies_genres m on r.movieid = m.movieid
        where m.genrecode like 'ADV'),
       (select avg(r.rating)
        from netflix.ratings100 r join netflix.movies_genres m on r.movieid = m.movieid
        where m.genrecode like 'COM'),
       (select avg(r.rating)
        from netflix.ratings100 r join netflix.movies_genres m on r.movieid = m.movieid
        where m.genrecode like 'MYS')
from netflix.customers c join netflix.ratings100 r on c.custid = r.custid
where c.numbkids < 4 and
group by c.numbkids

我正在显示只有 3 个或更少孩子的家庭(第 1 列),我需要显示每个家庭规模对动作类型(第 2 栏)、冒险类型(第 3 栏)、喜剧类型(第 4 栏)和神秘类型(第 5 栏)。在我看来,在取平均值之前,我似乎需要使用子查询按孩子的数量对这些类型列中的每一个进行分组,但我不知道如何在不添加额外列的情况下做到这一点。请帮忙!

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql join group-by subquery


【解决方案1】:

你是对的。您可以使用条件聚合,在标准中使用FILTER,但在大多数数据库中使用CASE

select c.numbkids "Number of Kids",
       avg(case when m.genrecode like 'ACT' then r.rating end),
       avg(case when m.genrecode like 'ADV' then r.rating end),
       avg(case when m.genrecode like 'COM' then r.rating end),
       avg(case when m.genrecode like 'MYS' then r.rating end)
from netflix.customers c join
     netflix.ratings100 r
     on c.custid = r.custid join
     netflix.movies_genres m
     on r.movieid = m.movieid
where c.numbkids < 4
group by c.numbkids

【讨论】:

  • 你是救生员!我也试过取一个子查询的平均值(显然没有用),不知道我怎么不认为取一个案例的平均值。谢谢!
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 2018-07-20
  • 2012-01-06
  • 1970-01-01
  • 2023-04-06
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多