我有下表
GroupID Sequence Name
1 10 Mary
1 25 Jack
1 17 Jill
2 3 Peter
2 42 Henry
2 50 Paul
以下查询返回给定组(1)和给定序列17的下一个最低序列(10)的行
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
还有另一种方法吗?我想避免
内部查询中的在哪里i.groupid = customerassignmentgroup .groupid
因为我需要将其转换为SubSonic中的查询
注意:我的数据库是SQL Server 2000
答案 0 :(得分:1)
如果你像使用ORDER BY一样,你可以这样做:
SELECT TOP 1 *
FROM dbo.customerassignmentgroup
WHERE groupid = 1 AND SEQUENCE < 17
ORDER BY SEQUENCE DESC
您可以通过执行以下操作来避免使用排序:
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 :(得分:1)
还有另一种方法可以做到这一点,但我不知道这是否有助于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