计算重复数据

时间:2015-11-11 17:52:56

标签: sql postgresql aggregate

我试图在表格中获得最大重复次数我尝试了很多方法,但无法使其正常工作。我要找的结果是:

"james";"108"

当我连接两个字段时,loca + locb重复两次,但其他字段没有重复,我尝试使用带有示例表结构的sqlfiddle链接以及我尝试过的查询... sqlfiddle link

我试过的查询是:

select * from (
select name,CONCAT(loca,locb),loca,locb 
, row_number() over (partition by CONCAT(loca,locb) order by CONCAT(loca,locb) ) as att

from Table1 
) tt
where att=1

please click这里您可以看到我尝试的完整示例表和查询。

Edite:添加完整的表格结构和数据:

CREATE TABLE Table1
    (name varchar(50),loca int,locb int)
;

insert into Table1 values ('james',100,2);
insert into Table1 values ('james',100,3);
insert into Table1 values ('james',10,8);
insert into Table1 values ('james',10,8);
insert into Table1 values ('james',10,7);
insert into Table1 values ('james',10,6);
insert into Table1 values ('james',0,7);
insert into Table1 values ('james',10,0);
insert into Table1 values ('james',10);
insert into Table1 values ('james',10);

我正在寻找的是得到(james,108),因为该值在整个数据中重复两次,有(james,10)的重复但是具有loca的null值所以零值和Null值只能忽略那些在(loca,locb)中都有值的值。

3 个答案:

答案 0 :(得分:0)

WITH concat AS (
  -- get concat values
    SELECT name,concat(loca,locb) as merged
    FROM table1 t1
    WHERE  t1.locb NOTNULL
    AND t1.loca NOTNULL
), concat_count AS (
  -- calculate count for concat values
    SELECT name,merged,count(*) OVER (PARTITION BY name,merged) as merged_count
    FROM concat
)
SELECT cc.name,cc.merged
FROM concat_count cc
WHERE cc.merged_count = (SELECT max(merged_count) FROM concat_count)
GROUP BY cc.name,cc.merged;

答案 1 :(得分:0)

SQL Fiddle

for (var j=0; j<15; j++){
  console.log(f(j,5));
}

/*
5,5
4,5
4,4
3,5
3,4
3,3
2,5
2,4
2,3
2,2
1,5
1,4
1,3
1,2
1,1
*/

答案 2 :(得分:0)

<强> Soundex and Metaphone algorithms

select name, 
       newvalue
from (
    select name,
           CONCAT(loca,locb) newvalue,   
           COUNT(CONCAT(loca,locb)) as total,
           row_number() over (order by COUNT(CONCAT(loca,locb)) desc) as att
    from Table1 
    where loca is not null 
      and locb is not null
    GROUP BY name, CONCAT(loca,locb)
) tt
where att=1