sql - 同时检索 'count where' 和总计数

标签 sql sqlite

我有一个餐厅评分和评论数据库,每家餐厅可能有 1 到 1000 条评论。

我首先尝试查找哪些餐厅的评论中包含“taco”这个词的评论最多 4+,然后我使用下面的代码让它工作:

    select id, count(id) from test where (comment like '%taco%') AND rating >= 3 group by id order by count(id) DESC;

因此,例如,如果 X 餐厅有 30 条 4+ 包含“taco”的评分评论,我会为该行获得“X|30”。

我想添加两个附加功能:
  • 列出每家餐厅的评论总数(无条件)
  • 对包括“taco”在内的所有餐厅评论进行平均评分。

  • 如果餐厅 X 总共有 150 条评论,其中 30 条评分为 4+,包括“taco”,这 30 条评论的平均评分为 2.5,我会得到:

    'X|30|150|2.5|'

    我如何得到这个结果?

    最佳答案

    这样的事情可能会奏效。

    select id
    , count(*) totalreviews
    , sum(case when rating >= 3 and comment like '%taco%' then 1 else 0 end) ratings4plus
    , avg(case when rating >= 3 and comment like '%taco%' then rating else null end) avgratings4plus
    from test
    group by id
    

    关于sql - 同时检索 'count where' 和总计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347194/

    相关文章:

    python-3.x - 是否可以在 EFS 中可靠地使用 SQLite?

    java - 从 sql 代码自动生成 java hibernate 代码

    database - SQlite NUMERIC 数据类型大小

    带有 Sqlite 的 Android - 如何检查表是否存在以及是否为空

    objective-c - 是否可以在核心数据中使用自定义 sqlite 函数?

    android - 如何在sdcard中创建私有(private)文件夹

    MySQL 查询 JOIN 返回 1 个空字段

    加载 mysqldump 文件时出现 sql 语法错误

    sql - 选择具有独特条件的条件

    mysql - 选择非重复记录