我有四个表格Candidates
,Parties
,Multiplier
和Votes
。
以下是表格的布局:
E.g。
+--------------+----------+----------------+--------+
| Candidate_ID | Surname | Name | Gender |
+--------------+----------+----------------+--------+
| 1 | BAREND | INNOCK CHARLIE | MALE |
| 2 | DU PREEZ | DONAVAN GARY | MALE |
| 3 | BERTELS | MEGAN MARIÉ | FEMALE |
| 4 | HOPLEY | CAITLIN TAYLOR | FEMALE |
+--------------+----------+----------------+--------+
E.g。
+----------+------------+-------+-------+
| Party_ID | Party_Type | Grade | Class |
+----------+------------+-------+-------+
| H1 | Head | | |
| T1 | TEACHER | | |
| 8N | LEARNER | 8 | N |
| 9N | LEARNER | 9 | N |
| 10N | LEARNER | 10 | N |
| 11N | LEARNER | 11 | N |
+----------+------------+-------+-------+
注意:N在A和J之间的范围,例如8A,8B,8C ...... 8J。
E.g。
+------------+------------+
| Party_Type | Multiplier |
+------------+------------+
| HEAD | 3 |
| TEACHER | 2 |
| LEARNER | 1 |
+------------+------------+
E.g。
+--------------+----------+--------+--------+--------+
| Candidate_ID | Party_ID | ClassA | ClassB | ClassC |
+--------------+----------+--------+--------+--------+
| 1 | H1 | 2 | 2 | 1 |
| 4 | 8C | 23 | 5 | 2 |
| 2 | H1 | 3 | 2 | 2 |
| 3 | 9D | 30 | 16 | 10 |
| 1 | T1 | 15 | 7 | 5 |
| 3 | T1 | 17 | 10 | 9 |
| 4 | T1 | 4 | 2 | 1 |
| 2 | 10E | 24 | 10 | 4 |
+--------------+----------+--------+--------+--------+
基本上,我正在尝试编写一个SQL语句来计算每个候选人的所有投票,然后按照从大多数到最少的投票对记录进行排序,如下所示:
+----+----------+----------------+--------+--------+--------+
| ID | Surname | Names | ClassA | ClassB | ClassC |
+----+----------+----------------+--------+--------+--------+
| 3 | BERTELS | MEGAN MARIÉ | 96 | 36 | 28 |
| 4 | HOPLEY | CAITLIN TAYLOR | 64 | 19 | 8 |
| 1 | BAREND | INNOCK CHARLIE | 36 | 20 | 13 |
| 2 | DU PREEZ | DONAVAN GARY | 33 | 16 | 10 |
+----+----------+----------------+--------+--------+--------+
到目前为止,我只能在不应用乘数的情况下统计所有投票:
SELECT C.Candidate_ID, C.Surname, C.Name, Sum(V.ClassA) AS ClassA, Sum(V.ClassB) AS ClassB, Sum(V.ClassC) AS ClassC
FROM Candidates C INNER JOIN Votes V ON C.Candidate_ID = V.Candidate_ID
GROUP BY C.Candidate_ID, C.Surname, C.Name;
所以我相信我的问题非常明确:我需要根据投票所来自的派对类型分别应用乘数。
答案 0 :(得分:1)
我认为应该这样做:
SELECT
C.Candidate_ID,
C.Surname,
C.Name,
SUM(V.ClassA * M.Multiplier) AS ClassA,
SUM(V.ClassB * M.Multiplier) AS ClassB,
SUM(V.ClassC * M.Multiplier) AS ClassC
FROM
( ( Candidates C
INNER JOIN Votes V ON C.Candidate_ID = V.Candidate_ID )
INNER JOIN Parties P ON V.Party_ID = P.Party_ID )
INNER JOIN Multiplier M ON P.Party_Type = M.Party_Type
GROUP BY
C.Candidate_ID,
C.Surname,
C.Name;