请求SQL乘以两列,然后用一些行的和除

时间:2016-01-28 06:23:16

标签: mysql sql

我有桌子

分数

id name score item_id
----------------------    
1   rikad  90  1
2   rikad  80  2
3  rikad 70 3
4  reza 80 1
5  reza 80 2
6  reza 100 3

id weight
----------
1  0.5
2  0.2
3  0.3

我想要输出新列调用last_score((得分x权重)/" 0.5 + 0.2 + 0.3(所有具有相同名称的权重之和)")

id name score item_id weight last_score
----------------------------------------
1   rikad  90  1 0.5  last_score
2   rikad  80  2 0.2 last_score
3  rikad 70 3 0.3 last_score
4  reza 80 1 0.5 last_score
5  reza 80 2 0.2 last_score
6  reza 100 3 0.3 last_score

我试过这个SQL:

SELECT 
    scores.id, scores.name,
    items.id, items.weight, 
    scores.score * items.weight AS 'last_score'
FROM 
    scores
JOIN 
    items ON items.id = scores.item_id

我需要将最后一个分数除以具有相同名称的所有权重的总和。但我不知道总重量。

2 个答案:

答案 0 :(得分:0)

您可以使用子查询按名称获取权重总和,并使用名称字段将其重新连接到主表:

SELECT scores.id, scores.name,items.id,items.weight, scores.score * items.weight/t.sum_weight AS 'last_score'
from scores
INNER JOIN items ON items.id = scores.item_id
INNER JOIN (SELECT scores.name, sum(items.weight) sum_weight
            FROM scores INNER JOIN items ON items.id = scores.item_id
            GROUP BY scores.name) t ON scores.name=t.name

答案 1 :(得分:-1)

选择S.id,S.name,S.score,S.item_id,I。[weight],  (cast(S.score as float)* cast(I. [weight] as float))/ sum(cast([weight] as float))作为LastScore  从分数S内部加入项目我  在s.id = i.id   S.id,S.name,S.score,S.item_id,I。[weight]