SQL-在'where''上方使用(partition by ...)'

时间:2019-01-09 14:24:55

标签: mysql sql

如何从标题多次运行的sql查询中获取结果?这显示了'PPP'的正确值,但过滤AND (count(*) over (partition by TITLE)) > 1无效。

任何帮助将不胜感激。

SELECT
    AAA,
    BBB,
    CCC,
    count(*) over (partition by TITLE) as PPP
FROM 
    my_tabel
WHERE
    AAA IS NOT NULL
    AND BBB = 'SOMETHING'
    AND (count(*) over (partition by TITLE)) > 1
;

返回的错误

ERROR: window functions are not allowed in WHERE

当我使用

...
    WHERE
        AAA IS NOT NULL
        AND BBB = 'SOMETHING'
;

一切正常显示,但是我想要一列PPP> 1

3 个答案:

答案 0 :(得分:3)

不能在WHERE子句中使用窗口函数,因为它们的结果是在获取满足WHERE子句的行之后计算的。在其周围再包裹一个SELECT,然后过滤掉此WHERE的{​​{1}}。

SELECT

答案 1 :(得分:0)

您还可以如下创建CTE,并使用CTE中的PPP添加过滤器:

    WITH cte AS(
    SELECT
        AAA,
        BBB,
        CCC,
        count(*) over (partition by TITLE) as PPP
    FROM 
        my_tabel
    WHERE
        AAA IS NOT NULL
        AND BBB = 'SOMETHING'
        )
    Select *
    FROM CTE
    WHERE PPP > 1;

答案 2 :(得分:0)

如果每行都有唯一的标识符(应使用),则只需使用exists

select t.*
from my_table t
where aaa is not null and bbb = 'something' and
      exists (select 1
              from my_table t2
              where t2.title = t.title and
                    t2.aaa is not null and t2.bbb = t.bbb and
                    t2.id <> t.id
            );

这是假设您实际上不需要其他用途的计数。