2015-11-11 101 views
1

我想獲得表中最大重複的整數我嘗試了很多方法,但無法使其工作。我在尋找的結果是:計數重複的數據

"james";"108"

由於這108當我Concat的兩個領域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); 

什麼我要找的是作爲價值被重複兩次在整個數據獲取(詹姆斯,108),還有的repetion (james,10)但是loca的值爲null,所以Zero值和Null值只能被視爲在兩個(loca,locb)中都有值。

+1

排序由你的分區上並沒有真正意義相同的值。請將示例數據添加到您的問題 - SQLFiddle不是真的可靠,目前不適合我。 –

+0

你好,謝謝我更新了樣本數據和數據.. – hi4ppl

+0

'CONCAT(loca,locb)'沒有意義。 'concat()'是連接字符串(文本)的值,而不是數字 –

回答

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; 
+0

嗨,謝謝你的回答和時間,但是當108的計數變化像現在一樣重複2次,這可以看作是數據集非常小,樣本但我需要在大數據集中運行它,我不知道cc.merged_count = 2 ...無論如何,這可以是動態的,所以它會自己挑選最大值......這些數據僅僅是樣本來指出我需要的。 .. – hi4ppl

+0

@ hi4ppl:你需要找到最出現的組合?請具體說明問題。 –

+0

嗨Dmity,是的,正是最重複的組合...我只給了108作爲例子抱歉混淆。 – hi4ppl

0

SQL Fiddle

select distinct on (name) * 
from (
    select name, loca, locb, count(*) as total 
    from Table1 
    where loca is not null and locb is not null 
    group by 1,2,3 
) s 
order by name, total desc 
+0

嗨謝謝,但這類記錄並沒有選擇頂部的特定記錄... – hi4ppl

+0

@ hi4ppl你只想要最上面的那個?將'limit 1'添加到查詢的底部。 –

+0

嗨,這是樣本記錄,只有當我在真實數據集中運行時,它將是百萬條記錄,所以如果我限制1,它將只選擇一條記錄,它不會從每個名稱返回1條記錄,gaol將爲concat選擇最大重複所有名字... – hi4ppl

0

SqlFiddleDemo

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 
+0

你解決了你的問題嗎? –