2

我有三张桌子:

学生

-------------------------------------------------------------
studentId        first        last        gender        weight
-------------------------------------------------------------
1                John         Doe         m             185
2                John         Doe2        m             130   
3                John         Doe3        m             250

升降机

-------------------
liftId        name        
-------------------
1             Bench Press
2             Power Clean  
3             Parallel Squat
4             Deadlift
5             Shoulder Press

学生缆车

------------------------------------------------
studentLiftId   studentId     liftId     weight 
------------------------------------------------
1                1            1          185
2                2            3          130   
3                3            1          190
4                1            2          120
5                2            1          155   
6                3            2          145
7                1            1          135
8                1            1          205   
9                2            3          200
10               1            3          150
11               2            2          110
12               3            3          250

我想要四个顶级列表:

  1. 卧推

  2. 平行深蹲

  3. 强力清洁

  4. 以上3项合计

我可以使用以下查询成功获取每个特定电梯的顶部列表:

SELECT s.studentId, s.first, s.last, s.gender, s.weight, l.name, sl.weight 
FROM Students s 
LEFT JOIN (
  SELECT *
  FROM StudentLifts 
  ORDER BY weight DESC
  ) sl ON sl.studentId = s.studentId 
  LEFT JOIN Lifts l ON l.liftId = sl.liftId 
  WHERE l.name = 'Bench Press' 
  AND s.gender = 'm' 
  AND s.weight > 170 
  GROUP BY s.studentId 
  ORDER BY sl.weight DESC

但是,我被困在如何为每个学生添加每个电梯的最高总数。我怎样才能首先找到每个学生在每个电梯中的最高总数,然后将它们相加以获得所有三个电梯的总和?

编辑

我正在寻找的结果集将类似于:

-------------------------------------------------
studentId    first    last    weight
-------------------------------------------------
3            John     Doe3    585
1            John     Doe     475
2            John     Doe2    465

我还忘了提到,我实际上想要两张名单,一张给 170 岁以上的学生,一张给 170 岁以下的学生。

4

1 回答 1

2
SELECT -- join student a total weight to the student table 
    A.studentId,
    A.first,
    A.last,
    C.totalWeight
FROM 
    Student A,  
    (
         SELECT  -- for each studet add the max weights 
             sum(B.maxWeight) as totalWeight, 
             B.studentID
         FROM (
             SELECT  -- for each (student,lift) select the max weight 
                 max(weight) as maxWeight, 
                 studentId, 
                 liftID
             FROM 
                 StudentLifts
             GROUP BY 
                 studentId,
                 liftID
         ) B
         GROUP BY 
            studentId
     ) C
WHERE 
    A.studentID = C.studentId 
    -- AND A.weight >= 170
    -- AND A.weight < 170
            -- pick one here to generate on of the two lists. 
于 2013-04-24T16:03:09.150 回答