如何使用sql命令查找团队

时间:2012-03-01 15:26:29

标签: sql sqlite

我正在使用SQLite数据库为正在进行的竞赛编写程序,我必须从完成数据中确定团队。有些学校参加了比赛,一支队伍由一所学校的四名(恰好四名)人组成。一所学校可以拥有多个团队。团队职位由成员职位的总和决定。参赛者存放在一张桌子上,上面有他们的最终位置名称和学校。

可以通过SQL查询完成,还是应该在代码中解决?

Example:
pos     name    school            pos    name     school
1      person1   foo               1     person1   foo
2      person2   foo               2     person2   foo
3      person3   bar               6     person6   foo
4      person4   bar               8     person8   foo
5      person5   bar     ->        3     person3   bar
6      person6   foo               4     person4   bar
7      person7   bar               5     person5   bar
8      person8   foo               7     person7   bar
9      person9   foo
10     person10  foo
11     person11  bar

2 个答案:

答案 0 :(得分:1)

我知道在SQLite中没有像ROW_NUMBER()OVER ...但我找不到类似于CROSS APPLY的东西。

如果存在与CROSS APPLY等效的内容,则可以执行以下操作。 (编辑:我注意到要求学校能够拥有多个团队。这个解决方案只适用于每个学校一个团队。就我所知,你需要一个递归的CTE和ROW_NUMBER,否则---这不是据我所知在SQLite中提供)

SELECT  TeamTable.*
FROM    Table
CROSS APPLY
    (
        SELECT  TOP 4 *
        FROM Table AS InnerTable
        WHERE   InnerTable.school = Table.School
        ORDER BY InnerTable.Pos
    ) AS TeamTable

如果没有,那么你可能不得不使用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

答案 1 :(得分:0)

select pos, name , schoole, count(school) as teamSize
from tableName
where teamSize = 4
groupby(school)