如果查找记录在SQL中的顺序?
比如我表里面有
id name pwd groupid detailid
1 a b 1 10
2 b b 2 11
3 c c 1 12
4 d d 1 22
5 e e 2 20
6 f f 1 30
我现在要查询出这样的结果,我现在知道groupid等于1,detailid等于30,s
q我现在想知道我要查询出的这条记录在groupid等于1的这个条件中排第几位.
比如我表里面有
id name pwd groupid detailid
1 a b 1 10
2 b b 2 11
3 c c 1 12
4 d d 1 22
5 e e 2 20
6 f f 1 30
我现在要查询出这样的结果,我现在知道groupid等于1,detailid等于30,s
q我现在想知道我要查询出的这条记录在groupid等于1的这个条件中排第几位.
select *,ord=(select count(*) from table where groupid=t.groupid and id<=t.ID)
from table t
where groupid=1 and detailid=30
INSERT @TB
SELECT 1, 'a', 'b', 1, 10 UNION ALL
SELECT 2, 'b', 'b', 2, 11 UNION ALL
SELECT 3, 'c', 'c', 1, 12 UNION ALL
SELECT 4, 'd', 'd', 1, 22 UNION ALL
SELECT 5, 'e', 'e', 2, 20 UNION ALL
SELECT 6, 'f', 'f', 1, 30SELECT COUNT(*)
FROM @TB
WHERE groupid=1 AND detailid>=30
/*
-----------
1
*/
--要保证这查出来的只有一条记录,如果不能会出现多条记录或不出来记录那请用max或isnull
--具体可根据自己的需求稍加修改
--这个你可以参考一下
create table [tab]([id] int,[name] varchar(1),[pwd] varchar(1),[groupid] int,[detailid] int)
insert [tab]
select 1,'a','b',1,10 union all
select 2,'b','b',2,11 union all
select 3,'c','c',1,12 union all
select 4,'d','d',1,22 union all
select 5,'e','e',2,20 union all
select 6,'f','f',1,30select * from tabselect place from(
select *,Place=(SELECT COUNT(id) FROM tab WHERE id<a.id)+1
from [tab] a) t where groupid=1 and detailid=30/*
place
-----------
6(所影响的行数为 1 行)*/select *,Place=(SELECT COUNT(id) FROM tab WHERE id<a.id)+1
from [tab] a/*
id name pwd groupid detailid Place
----------- ---- ---- ----------- ----------- -----------
1 a b 1 10 1
2 b b 2 11 2
3 c c 1 12 3
4 d d 1 22 4
5 e e 2 20 5
6 f f 1 30 6(所影响的行数为 6 行)
*/
drop table tab
declare @a int --第几位
select @a=count(1) from tb where groupid = 1 and detailid <= 30
SELECT COUNT(distinct detailid)+1
FROM @TB
WHERE groupid=1 AND detailid>30
id name pwd groupid detailid
1 a b 1 10 3 c c 1 12
4 d d 1 22 6 f f 1 30
我现要知道detailid=30在上面查询出来的记录中是排第几位,上面四条记录,当然是排第四位,
我就是得到"4"这个值..请问应该如何写sql语句