我知道有沒有像ROW_NUMBER()OVER ......在SQLite的,但我不能找到類似於CROSS APPLY什麼東西。
如果有相當於CROSS APPLY的東西,那麼您可以執行以下操作。 (編輯:我注意到要求學校能夠有多個團隊,這個解決方案只適用於每個學校的一個團隊,就我所知,你需要一個遞歸的CTE和ROW_NUMBER,否則---哪些不是SQLite中可據我所知)
如果沒有,那麼你就可能要使用while循環和臨時表來填補這個。如果是這樣的話,那麼使用SQL沒有真正的收益,我會建議去代碼路由。
編輯: 但是,這是臨時表解決方案所要求的。您需要內一段時間,因爲你可以有學校內部的多個團隊(這是我之前曾忽視,使得CROSS APPLY沒有遞歸CTE和ROW_NUMBER,已編輯承認解決方案不起作用)
CREATE TABLE #SchoolList
(Id INT IDENTITY(1,1), School VARCHAR(50))
INSERT INTO #SchoolList
SELECT DISTINCT School
FROM TeamTable
CREATE TABLE #TeamList
(TeamNumber INT IDENTITY(1,1), Pos INT, Name VARCHAR(50),
School VARCHAR(50))
DECLARE @CurrentSchool VARCHAR(50), @CurrentSchoolPos INT
DECLARE @CurrentSchoolLookupId INT
SET @CurrentSchoolId = 1
WHILE EXISTS (SELECT 1 FROM #SchoolList WHERE Id > @CurrentSchoolLookupId)
BEGIN
SELECT @CurrentSchool = School FROM #SchoolList
WHERE Id = @CurrentSchoolLookupId
SET @CurrentSchoolPos = SELECT TOP 1 Pos FROM TeamTable
WHERE School = @CurrentSchool
ORDER BY POS
WHILE ISNULL(@CurrentSchoolPos, 0) > 0
BEGIN
INSERT INTO #TeamList
SELECT Pos, Name, School
FROM TeamTable
WHERE School = @CurrentSchool AND Pos = @CurrentSchoolPos
SET @CurrentSchoolPos = SELECT TOP 1 Pos FROM TeamTable
WHERE School = @CurrentSchool
AND Pos > @CurrentSchoolPos ORDER BY POS
END
SET @CurrentSchoolLookupId = @CurrentSchoolLookupId + 1
END
SELECT * FROM #TeamList
究竟是4還是> = 4? – 2012-03-01 15:55:45