SQL select查询以查找特定记录计数的记录

时间:2015-11-25 10:37:06

标签: sql sql-server count

Table: MyData
============================
id | Name | Surname
----------------------------
1  | AB   | ABAB
2  | CD   | CDCD
3  | EF   | EFEF
4  | CD   | CDCD
5  | CD   | CDCD
6  | AB   | ABAB
7  | CD   | CDCD 
8  | CD   | CDCD

选择id作为给定计数的特定名称的记录,即:首先,我得到不同的名称

AB
CD
EF

然后我想得到ID每个帐户的3次出现,所以从AB开始

For name AB
Start with id = 1
eg: SELECT id FROM MyData WHERE id >= 1 Name = 'AB' and count <= 3 --Should return id=6 as there are only 2 occurrences so it should just return the last one

For name CD
Start with id = 1
eg: SELECT id FROM MyData WHERE id >= 1 Name = 'CD' and count <= 3 --Should return id=5 as record 5 contains the 3 occurrence
Set id = returned id + 1 so start id = 6
eg: SELECT id FROM MyData WHERE id >= 6 Name = 'CD' and count <= 3 --Should return id=8 as from id 6 the last occurrence is at id 8

For name EF
Start with id = 1
eg: SELECT id FROM MyData WHERE id >= 1 Name = 'EF' and count <= 3 --Should return id=3

我很难找到一种干净的方法来完成这个ms sql。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

For name AB
Start with id = 1
eg: SELECT id FROM MyData WHERE id >= 1 Name = 'AB' and count <= 3

尝试以下查询并相应地进行更改 -

select top 1 id from (SELECT top 3 id FROM PPBSample WHERE id >= 1 and Name = 'AB' order by id ) as test order by id desc

注意 - 根据您的要求,在上述查询中相应地更改id >= your numberName