我需要选择所有行,从第一行开始,满足条件,直到最后一行,满足另一个条件。如果没有行满足第二个条件,我需要所有的行。我想出了这个问题:
SELECT * FROM History WHERE ID BETWEEN
(
SELECT TOP 1 ID FROM History WHERE
{FirstCondition} AND {GeneralCondition} ORDER BY ID ASC
) AND (
SELECT TOP 1 ID FROM History WHERE
{SecondCondition} AND {GeneralCondition} ORDER BY ID DESC
) AND {GeneralCondition}
Hovewer它没有选择任何东西,任何一行都不满足第二个条件。我的问题是,单个查询甚至可以实现这一点吗?或者我应该在应用程序方面进行进一步排序吗?
实施例:
需要为OrderID=4
(GeneralCondition)选择所有行,并使用UserID=3
(FirstCondition)进行评论,直到UserID=6
(SecondCondition)
表
Case 1: Case 2:
ID|OrderID|UserID ID|OrderID|UserID
----------------- -----------------
1 | 4 | 4 1 | 4 | 4
2 | 4 | 3 2 | 4 | 3
3 | 4 | 4 3 | 4 | 4
4 | 4 | 6 4 | 4 | 7
5 | 4 | 4 5 | 4 | 4
6 | 5 | 4 6 | 5 | 4
7 | 5 | 4 7 | 5 | 4
期望的输出:
Case 1: Case 2:
ID|OrderID|UserID ID|OrderID|UserID
----------------- -----------------
2 | 4 | 3 2 | 4 | 3
3 | 4 | 4 3 | 4 | 4
4 | 4 | 6 4 | 4 | 7
5 | 4 | 4
答案 0 :(得分:1)
答案 1 :(得分:1)
条件汇总可能有更好的计划
SELECT *
FROM History
WHERE ID BETWEEN
(
SELECT MIN(ID) FROM History WHERE {FirstCondition} AND {GeneralCondition}
) AND
(
SELECT CASE WHEN MAX(CASE WHEN {SecondCondition} THEN ID END) IS NULL
THEN MAX(ID)
ELSE MAX(CASE WHEN {SecondCondition} THEN ID END)
END
FROM History
WHERE {GeneralCondition})
)
AND {GeneralCondition}