SQL Server: Queries the next lower value for a given parameter

I have the following table

GroupID Sequence    Name
1             10        Mary
1             25        Jack
1             17        Jill
2              3        Peter
2             42        Henry
2             50        Paul

The following query returns a string with the following lower sequence (10) for a given group (1) and the given sequence 17

SELECT TOP 1 *
FROM   dbo.customerassignmentgroup
WHERE  groupid = 1
       AND SEQUENCE < (SELECT MAX(SEQUENCE)
                       FROM   dbo.customerassignmentgroup i
                       WHERE  i.groupid = customerassignmentgroup .groupid)
       AND manualsequence < 17
ORDER  BY SEQUENCE DESC

Is there any other way to do this? I try to avoid

WHERE i.groupid = customerassignmentgroup.groupid

in an internal query because I need to convert this to a query in SubSonic

Note. My database is SQL Server 2000

+3
source share
2 answers

If you use ORDER BY as you can, you can simply do:

SELECT TOP 1 *
FROM   dbo.customerassignmentgroup
WHERE  groupid = 1 AND SEQUENCE < 17
ORDER  BY SEQUENCE DESC

You can avoid sorting by doing:

SELECT *
FROM   dbo.customerassignmentgroup t1
WHERE  t1.groupid = 1
   AND t1.SEQUENCE = (SELECT MAX(t2.SEQUENCE)
                   FROM   dbo.customerassignmentgroup t2
                   WHERE  t2.groupid = 1 AND t2.SEQUENCE < 17)
+1
source

, , SubSonic. FROM.

SELECT TOP 1 *
FROM   dbo.customerassignmentgroup i
       INNER JOIN (SELECT MAX(SEQUENCE) SEQUENCE, groupid
                       FROM   dbo.customerassignmentgroup
                       GROUP BY groupid) maxSeq
       ON  i.groupid = maxSeq.groupid
          and i.SEQUENCE < maxSeq.SEQUENCE 
          and i.groupid = maxSeq.groupid

WHERE  groupid = 1

       AND manualsequence < 17
ORDER  BY SEQUENCE DESC
+1

All Articles