Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何使用`OVER(分区依据…)进行区分`_Sql_Database_Postgresql_Greatest N Per Group_Window Functions - Fatal编程技术网

Sql 如何使用`OVER(分区依据…)进行区分`

Sql 如何使用`OVER(分区依据…)进行区分`,sql,database,postgresql,greatest-n-per-group,window-functions,Sql,Database,Postgresql,Greatest N Per Group,Window Functions,如何通过…使用超额分配来区分 我也希望使用下面的查询,这样我就可以将其用作内部查询 select ACCT_TYPE_CD, ACCT_ID, COUNT(*) OVER(PARTITION BY ACCT_TYPE_CD, ACCT_ID) AS CNT from ACCOUNT ACCT; acct_type_cd |ACCT_ID |cnt | -------------|------------|----| EMPID |1 |3 |

如何通过…使用超额分配来区分

我也希望使用下面的查询,这样我就可以将其用作内部查询

select  ACCT_TYPE_CD, ACCT_ID,  COUNT(*) OVER(PARTITION BY ACCT_TYPE_CD, ACCT_ID) AS CNT
from ACCOUNT ACCT; 

acct_type_cd |ACCT_ID     |cnt |
-------------|------------|----|
EMPID        |1           |3   |
EMPID        |1           |3   |
EMPID        |1           |3   |
EMPID        |1066        |3   |
EMPID        |1066        |3   |
EMPID        |1066        |3   |
这是你想要的吗

select *
from (
    select  acct_type_cd, acct_id, count(*) over(partition by acct_type_cd, acct_id) as cnt
    from account acct
) t
where cnt > 1
也就是说:您不能在查询的where子句中使用窗口函数-您需要在子查询中计算窗口计数,然后在外部查询中进行过滤

或者,如果希望仅使用窗口函数生成与第一个查询相同的结果,则可能需要查找行号:

也就是说,我真的不知道你为什么要这么做;在第一个查询中使用聚合可能总是比在第二个查询中使用两个窗口函数和过滤更有效

下面是使用distinct on的最后一个选项:


你能告诉我最终的查询是什么吗?如果你不想重复,并且只选择那些列,那么你的第二个查询看起来应该是一个简单的分组查询。@Marth-我不知道你的意思,你能不能在查询中显示出来?如果第一个查询符合你的要求,那么你为什么要另一个查询?不,这不是我想要的,我想要独一无二的记录。我希望第二次查询的第一次查询结果为well@JeffCook例如我不明白你的意思。请编辑您的问题以显示您想要的结果好吗?请正确阅读。我希望第二个查询的第一个查询的输出您的上一个查询有意义,是的,让我试着在我想要使用它的较大查询中使用它。
select *
from (
    select  acct_type_cd, acct_id, count(*) over(partition by acct_type_cd, acct_id) as cnt
    from account acct
) t
where cnt > 1
select *
from (
    select  
        acct_type_cd, 
        acct_id, 
        count(*) over(partition by acct_type_cd, acct_id) as cnt,
        row_number() over(partition by acct_type, acct_id order by acct_type, acct_id) rn
    from account acct
) t
where cnt > 1 and rn = 1
select distinct on (acct_type_cd, acct_id)
    acct_type_cd, 
    acct_id, 
    count(*) over(partition by acct_type_cd, acct_id) as cnt
from account acct
order by acct_type_cd, acct_id