如何使用SQL获取具有相同值的行计数?

时间:2011-11-11 12:23:10

标签: sql select grouping

我有一个包含列的表:id和created(datetime)

id  created
6   2011-11-04 20:32:09.673
5   2011-11-04 20:32:09.673
4   2011-11-04 20:29:55.000
3   2011-11-04 20:29:55.000

如何编写sql,它将返回没有,具有2或具有2个以上相等创建日期的记录的计数。它可以是3个单独的平方。

谢谢

2 个答案:

答案 0 :(得分:2)

如果我正确理解你的问题,我相信这应该可以解决问题,返回多次发生的创建日期。

这个将获得超过2的人。

SELECT
    created
    ,COUNT(*) as [occurrences]
FROM
    tableName
GROUP BY
    created HAVING COUNT(*) > 2

交换> 2 = a = 2得到2与2完全相同而且= 1得到那些只有1次出现的那些。

答案 1 :(得分:0)

尝试:

select case reccount
           when 1 then 'No matches'
           when 2 then 'Exactly 2 matches'
           else 'More than 2 matches'
       end as number_of_matches,
       count(*) as distinct_dates,
       sum(reccount) as record_count
from (select created,
             count(*) reccount
      from mytable
      group by created) v
group by
case reccount
           when 1 then 'No matches'
           when 2 then 'Exactly 2 matches'
           else 'More than 2 matches'
       end