duanmiao6695 2018-10-25 20:51
浏览 32
已采纳

如何在INNER JOIN中显示课程名称?

I have two tables: users and courses. Inside users table i have filed course where i have course id. Inside courses table i have just ID and NAME.

I need to get popular course. I do request:

SELECT u.course, COUNT(*) as freq FROM users u INNER JOIN courses c ON u.course = c.id GROUP BY u.course

As a result: id => freq. But i need to replace ID to NAME of course. How?

Thanks.

  • 写回答

4条回答 默认 最新

  • dongnanman9093 2018-10-25 21:25
    关注

    You don't say what database you use, but I would assume you can use CTEs since most modern databases do. Your query can be written as:

    with x as (
      select course, count(*) as freq from users group by course
    ),
    y as (
      select max(freq) as max_freq from x
    )
    select c.name, x.freq
      from x
      join y on x.freq = y.max_freq
      join courses c on c.id = x.course
    

    This query has the [desirable?] side effect that it shows more than one course, if there are more than one tied in first place.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?