SQL - 与 group_by 相关的平均记录数

SQL - Average number of related records with group_by

我有 table 条记录(我们称它们为电视节目),其中有一个 air_date 字段。

我还有另一个 table 广告,它们由 show_id 字段相关。

我正在尝试获取每个日期每个节目的平均广告数(使用指定节目的 where 子句)。

我目前有这个:

SELECT 
 `air_date`,
 (SELECT COUNT(*) FROM `commercial` WHERE `show_id` =  `show`.`id`) AS `num_commercials`,  
FROM `show` 
WHERE ...

这给了我这样的结果:

air_date  | num_commercials
2015-6-30 | 6
2015-6-30 | 3
2015-6-30 | 8
2015-6-30 | 2
2015-6-31 | 9
2015-6-31 | 4

当我执行 GROUP_BY 时,它只会给我其中一条记录,但我想要每个 air_date.

的平均值

不太确定我是否清楚你想要什么 - 但这样做可以吗

SELECT `air_date`, 
AVG((SELECT COUNT(*) FROM `commercial` WHERE `show_id` =  `show`.`id`)) AS  `num_commercials`,  
FROM `show` 
WHERE .....
GROUP BY `air_date`

(注意 AVG 函数需要双括号)

您可以使用子查询 select air_date/show 的商业广告计数,然后使用外部查询 select 每个 air_date 的平均商业广告计数。

像这样的东西应该可以工作:

select air_date, avg(num_commercials)
from 
(
  select show.air_date as air_date, 
    show.id as show_id,
    count(*) as num_commercials
  from show 
    inner join commercial on commercial.show_id =  show.id
  group by show.air_date, show.id
  where ...
) sub
group by air_date