0

MySql の問題で立ち往生しています。助けてください。

この例では、2 つのテーブルがあり、1 つは多数の競技者の結果を示し、もう 1 つはチームを構成する 3 人の競技者を定義します。実際には、他にも多くのテーブルがありますが、この問題を説明するためにそれらは実際には必要ありません。

Table with results for each competitor
| competitor_id | result1 | result2 | result3 | result4 |
|       1       |    1    |    1    |    1    |     1   |
|       2       |    1    |    2    |    2    |     1   |
|       3       |    2    |    3    |    2    |     1   |
|       4       |    1    |    5    |    3    |     2   |
|       5       |    4    |    3    |    2    |     3   |
|       6       |    3    |    2    |    1    |     2   |
|       7       |    2    |    1    |    4    |     2   |
|       8       |    2    |    1    |    2    |     1   |
|       9       |    1    |    2    |    3    |     2   |

Table showing teams
| team_id | competitor1 | competitor3 | competitor3 |
|    1    |      1      |       3     |       4     |
|    2    |      2      |       8     |       9     |
|    3    |      7      |       6     |       5     |

ここで、各チームの合計を取得するクエリを作成したいと思います。合計結果で desc をソートする必要があるため、1 つのクエリ (おそらくサブクエリを使用) が必要です。

つまり、各チームの合計結果について team.id で並べ替えられた結果セットが必要です。

誰?

編集:これは、望ましい結果を示す更新です

まず、各競技者の結果を合計しましょう。

Competitor 1: 1+1+1+1=4
Competitor 2: 1+2+2+1=6
Competitor 3: 2+3+2+1=8
Competitor 4: 1+5+3+2=11
Competitor 5: 4+3+2+3=12
Competitor 6: 3+2+1+2=8
Competitor 7: 2+1+4+2=9
Competitor 8: 2+1+2+1=6
Competitor 9: 1+2+3+2=8

次に、チーム表を見てみましょう。

Team 1 consists of competitors 1, 3 and 4.  
Team 2 consists of competitors 2, 8 and 9.  
Team 3 consists of competitors 7, 6 and 5.  

Total sum of team with id = 1 is 4+8+11=23  
Total sum of team with id = 2 is 6+6+8=20  
Total sum of team with id = 3 is 9+8+12=29  

これらすべてを考慮して、結果セットを次のようにしたいと思います

| id | team_sum |
| 3  |    29    |
| 1  |    23    |
| 2  |    20    |
4

1 に答える 1

1

competitorsデータベースを再設計してみませんかteam?

Competitors Table:
`competitor_id`, `team_id`, `result1`, `result2`, `result3`, `result4`

Team Table:
`team_id`, `team_name`

そして、クエリは次のように非常に簡単になります。

SELECT A.team_id, B.team_name, SUM(result1+result2+result3+result4) as TotalResult
FROM competitors A
INNER JOIN team B
ON A.team_id=B.team_id
GROUP BY A.team_id, B.team_name

私のフィドルのデモを見る

于 2013-06-08T05:46:41.073 に答える