SQL查询获取带有count的所有重复记录

时间:2016-06-30 16:12:10

标签: sql sql-server

我在某个列(state)中有一个包含重复数据的表。我需要获取所有行并显示重复记录的COUNT()

样本数据

name     state  email
----     ----   -----
john     ny     john@ny.com
smith    ny     smith@ny.com
bryan    nj     bryan@nj.com

我需要编写一个SQL查询来显示这样的记录,其中包括每行上重复state个值的数量:

name     state  email         count
----     ----   -----         -------
john     ny     john@ny.com      2
smith    ny     smith@ny.com     2
bryan    nj     bryan@nj.com     1

4 个答案:

答案 0 :(得分:3)

您可以使用COUNT(*) State PARTITION来执行此操作:

Select  name, state, email,
        Count(*) Over (Partition By State) As Count
From    YourTable

答案 1 :(得分:1)

DECLARE @Table1 TABLE 
    (name varchar(5), state varchar(2), email varchar(12))
;

INSERT INTO @Table1
    (name, state, email)
VALUES
    ('john', 'ny', 'john@ny.com'),
    ('smith', 'ny', 'smith@ny.com'),
    ('bryan', 'nj', 'bryan@nj.com')
;

脚本

SQL SERVER

 select  name,state,email,COUNT(state)OVER(PARTITION BY state  )Cnt from @Table1

MySQL

Select T.name, T.state, T.email,TT.cnt from @Table1 T
INNER JOIN (select COUNT(state)cnt,state from @Table1
GROUP BY state)TT
ON T.state = TT.state
ORDER BY cnt Desc

答案 2 :(得分:0)

您可以使用汇总上的from

        select state, count, b.name, b.email from 
        ( select a.state as state , a.count(*) as count
        from my_table as a 
        group by a.state ) t 
        inner join my_table as b on b.state = t.state

答案 3 :(得分:0)

要显示您的显示:

SELECT name ,
       [state] ,
       email, 
       COUNT(*) OVER (PARTITION BY state) as [count]
       FROM myTable
       ORDER BY [state] DESC;