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

use*_*609 1 sql sqlite

我有一个餐厅评级和评论数据库,每个餐厅可以有1到1000个评论.

我首先尝试找到哪些餐馆评价最多4+评论中包含"taco"这个词,我得到了以下代码:

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

因此,例如,如果餐厅X有30个4+评级,包括'taco',那么我会得到'X | 30'.

我想添加两个额外的功能:

  1. 列出每家餐厅的评论总数(没有任何条件)
  2. 给出包括'taco'在内的所有餐厅的评价的平均评分.

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

'X | 30 | 150 | 2.5 |'

我如何得到这个结果?

Dan*_*cuk 6

这样的事可能有用.

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
Run Code Online (Sandbox Code Playgroud)