SQL查询根据条件计算值

时间:2011-02-24 15:29:02

标签: mysql sql

我有三个相关的表格:

Evaluations:
EvalID
WorktypeID
PointsPossible

Items:
EvalID
ItemID
Value
QuestionID

Question_Worktype:
WorkTypeID
QuestionID
Points

每个评估都有多个项目,每个项目都有一个QuestionID / WorkTypeID对,与Question_Worktype中的条目相关,其中得分为。

Items.Value是项目是否正确。

我想要一个查询返回评估所有项目的总分数,只有在项目的价值为1时​​才会获得分数。

我的目标是获得:

Eval_ID, Total Points (calculated), Points Possible

我似乎无法将自己的大脑包裹起来。

编辑:我忘了一个重要的部分:

我还有一张表:

qa_edits:
EditID
ItemID
NewValue
Date

如果某人编辑了该值,则会将其存储在此处,我确实需要根据项目的最新编辑进行计算(如果有)或项目值(如果没有)。

2 个答案:

答案 0 :(得分:1)

我认为这应该有效:

select e.Eval_ID, sum(qw.Points) as TotalPoints, e.PointsPossible
   from Evaluations e
   left join Items i on e.Eval_ID = i.Eval_ID and i.Value = 1
   join Questions_WorkType qw on qw.QuestionID = i.QuestionID
   group by e.Eval_ID, e.PointsPossible

答案 1 :(得分:1)

从编辑表开始,获取每个项目的最新编辑内容:

SELECT
    M.ItemId,
    COALESCE(Q.Value, I.Value) as Value,
    I.QuestionId
FROM (
    SELECT
       I.ItemId,
       MAX(Date) as LastEditDate
    FROM Items as I
    LEFT OUTER JOIN QA_Edits as E ON
       I.ItemId = E.ItemId
    GROUP BY
       I.ItemId
) as M
LEFT OUTER JOIN QA_Edits as Q ON
    M.ItemId = Q.ItemId
    AND M.LastEditDate = Q.Date
LEFT OUTER JOIN Items as I ON 
    M.ItemId = Q.ItemId
    AND M.LastEditDate IS NULL

我建议一个观点 - 我们称之为LatestItems

然后,回到Blorgbeard's

select
    e.Eval_ID, 
    sum(qw.Points) as TotalPoints, 
    e.PointsPossible
from Evaluations e
join LatestItems i on 
    e.Eval_ID = i.Eval_ID 
    and i.Value = 1
join Questions_WorkType qw on 
    qw.QuestionID = i.QuestionID
group by 
    e.Eval_ID, e.PointsPossible