2017-02-28 56 views
1

從這個表:計數的重複值的兩列在SQL Server

Number Value 
1  a 
2  b 
3  a 
2  c 
2  b 
3  a 
2  b 

我需要NumberValue讓所有重複的行數,即5

感謝。

+0

你需要兩列重複計數..? – Mansoor

+4

儘管數據集簡單,但我其實並不瞭解您的問題。這裏您的預期產出是什麼? –

+0

你如何得到'3'的結果? – Wanderer

回答

2

我覺得這個查詢你想要什麼:

SELECT SUM(t.cnt) 
FROM 
(
    SELECT COUNT(*) cnt 
    FROM table_name 
    GROUP BY number, value 
    HAVING COUNT(*) > 1 
)t; 
+0

是的,這有所幫助。最後「t」意味着什麼? – Feofilakt

+0

@Feofilakt't'只是一個別名名稱 –

+2

@Feofilakt由於[Tim Biegeleisen](http://stackoverflow.com/users/1863229/tim-biegeleisen)說,你最好不僅提供樣本數據,而且還提供下一次需要的結果。或者如此多的答案,只有一個可以明白你的觀點。 – Blank

0
Select 
    count(distinct Number) as Distinct_Numbers, 
    count(distinct Value) as Distinct_Values 
from 
    Table 

這顯示了每列中有多少個不同的值。這有幫助嗎?

0

我想你的意思是唯一編號的數量 - 值對,您可以使用:

SELECT count(*) 
FROM 
(SELECT ROW_NUMBER() OVER (PARTITION BY number, value ORDER BY (select 1)) from mytable rnk) i 
where i.rnk = 1 
0

雙方提供一個行號分區列和兩列的順序。再算上行數,其中行數大於1

查詢

;with cte as(
    select [rn] = row_number() over(
     partition by [Number], [Value] 
     order by [Number], [Value] 
    ), * 
    from [your_table_name] 
) 
select count(*) from cte 
where [rn] > 1; 
1

也許這樣的事情還大嗎?

select value,number,max(cnt) as Count_distinct from (
     select *,row_number() over (partition by value,number order by number) as cnt 
    from #sample 
    )t 
    group by value,number 

輸出

+---------------------------------+ 
    | Value | Number | Count_Distinct | 
    | a | 1 |  1  | 
    | b | 2 |  3  | 
    | c | 2 |  1  | 
    | a | 3 |  2  | 
    +---------------------------------+ 
0

可能是此查詢可以幫助你

SELECT * FROM [DBO] [Sample_table1]

;隨着 DupContactRecords(數,值,DupsCount) AS ( SELECT number R,值,COUNT()AS TOTALCOUNT FROM [Sample_table1] GROUP BY數目,值HAVING COUNT()> 1 ) --to得到duplicats /* SELECT * FROM DupContactRecords */ SELECT SUM(DupsCount) FROM DupContactRecords enter image description here