SQL Server中两列的重复值计数

时间:2017-02-28 05:23:33

标签: sql sql-server

从此表中:

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

我需要按NumberValue计算所有重复行数,即5.

感谢。

6 个答案:

答案 0 :(得分:2)

我认为这个查询就是你想要的:

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

答案 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       |
   +---------------------------------+

答案 2 :(得分:0)

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

这表示每列中有多少个不同的值。这有帮助吗?

答案 3 :(得分:0)

我认为你的意思是唯一数字 - 值对的数量,你可以使用:

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

答案 4 :(得分:0)

按列提供行号分区,并按两列排序。然后计算行数大于1的行数。

<强>查询

    SELECT time AS 'InTime(Mode-3)',
      (SELECT TOP 1 time FROM timeTable
          WHERE mode = 1 
            AND id = outerTable.id 
            AND date = outerTable.date 
            AND time > outerTable.time 
          ORDER BY date, time) AS 'OutTime(Mode-1)' 
    FROM timeTable AS outerTable 
    WHERE mode = 3

答案 5 :(得分:0)

可能是这个查询可以帮到你

从[dbo]中选择*。[Sample_table1]

; WITH DupContactRecords(数字,值,DupsCount) 如 ( SELECT编号,值,COUNT()AS TotalCount FROM [Sample_table1] GROUP BY编号,值HAVING COUNT()&gt; 1 ) - 获得重复项 / * select * from DupContactRecords * / SELECT sum(DupsCount)FROM DupContactRecords enter image description here