SQL Window 函数 - 无法分组时如何处理

SQL Window Function - How to handle since unable to Group By

这是我第一次在这里发帖。几个月来我一直在悄悄浏览论坛。

我正在尝试显示类别名称、四分位数和每个四分位数的标题数。这是我的 SQL 代码:

SELECT name, standard_quartile, count
FROM 
     (SELECT c.name, ntile(4) over (order by f.rental_duration) as 
     standard_quartile, count(f.title) as count
     FROM category c
     JOIN film_category fc ON c.category_id=fc.category_id
     JOIN film f ON fc.film_id=f.film_id 
     WHERE c.name='Animation' OR c.name='Children' OR c.name='Classics' OR 
     <BR>c.name='Comedy' OR c.name='Family' OR c.name='Music'
     <BR>GROUP BY c.name, f.rental_duration
     <BR>) t1
GROUP BY 1, 2, 3
ORDER BY 1,2

但是,因为我无法按四分位数分组(这是一个 window 函数),所以它没有显示我想要的结果。我认为将它放在子查询中可能会使它起作用,但事实并非如此。我认为另一个问题是一个四分位数可以有多个与之关联的租赁持续时间数字。

这是它的样子:

动画 1 12
动画 1 18
动画 2 9
动画 3 13
动画 4 14
Children 1 12
Children 2 9
Children 2 15
Children 3 13
Children 4 11

如果有人能指出正确的方向或有帮助的提示,我将不胜感激。

计数和分组是我要解决的问题。如果您在显示结果的片段中看到,Animation 有两个 1 四分位数,Children 有两个 2 四分位数。每个应该有一个。但是因为它是一个 window 函数,所以我不能按四分位数分组,所以它按 rental_duration 分组。

谢谢! :)

PS - 它应该是这样的:

screenshot of expected query results

select name , standard_quartile, sum(count)
    FROM(
    SELECT name, standard_quartile, count
    FROM 
         (SELECT c.name, ntile(4) over (order by f.rental_duration) as 
         standard_quartile, count(f.title) as count
         FROM category c
         JOIN film_category fc ON c.category_id=fc.category_id
         JOIN film f ON fc.film_id=f.film_id 
         WHERE c.name='Animation' OR c.name='Children' OR c.name='Classics' OR 
         <BR>c.name='Comedy' OR c.name='Family' OR c.name='Music'
         <BR>GROUP BY c.name, f.rental_duration
         <BR>) t1
    GROUP BY 1, 2, 3) t2
group by 1,2
ORDER BY 1,2

我认为您只希望在外部查询中使用 group by:

SELECT name, standard_quartile, count(*)
FROM (SELECT c.name,
             ntile(4) over (order by f.rental_duration) as standard_quartile
     FROM category c JOIN
          film_category fc
          ON c.category_id = fc.category_id JOIN
          film f
          ON fc.film_id = f.film_id 
     WHERE c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
    ) t1
GROUP BY name, standard_quartile
ORDER BY name, standard_quartile;

另请注意 in 用于类别列表。