我是SQL的新手所以原谅任何新手的错误......
每周,用户都会回答10个问题,我会跟踪他们的进展情况。对于每个用户,我想找到正确回答问题的总分,按周显示。所以结果看起来像这样:
userID = 1
weekID = 3
TotalPoints = 5
以下是我的专栏:
userID,weekID,
QuestionA,QuestionA_ID,A_Correct,PointsA
QuestionB,QuestionB_ID,B_Correct,PointsB
TotalPoints (PointsA + PointsB)
以下是我的问题:
SELECT userID, weekID,
SUM(DISTINCT PointsA + PointsB) as TotalPoints
FROM Results [LIMIT 0,3],
(SELECT SUM(DISTINCT PointsA)
FROM Results
WHERE A_Correct = "Y" and userID = "1"),
(SELECT SUM(DISTINCT PointsB)
FROM Results
WHERE B_Correct = "Y" and userID = "1")
WHERE userID = "1" and weekID < "10"
GROUP BY weekID ORDER BY weekID ASC;
好像我从每周都得到总计的总数而不是每周的总数。关于我哪里出错的任何想法?如何更好地做到这一点?提前谢谢。
答案 0 :(得分:1)
我想你想要这样的东西:
select userID, weekID,
sum(case when A_Correct = 'Y' then PointsA else 0 end) as PointsA,
sum(case when B_Correct = 'Y' then PointsB else 0 end) as PointsB,
(sum(case when A_Correct = 'Y' then PointsA else 0 end) +
sum(case when B_Correct = 'Y' then PointsB else 0 end)
) as TotalPoints
from results
where weekId < 10
group by userId, weekID;
我不知道limit
在查询中应该做什么,也不知道DISTINCT
。如果您只想选择一个用户,请在where
之前添加group by
子句。
答案 1 :(得分:0)
SELECT userID
, weekID
, SUM(case when A_Correct = 'Y' then pointsA else 0 end)
+ SUM(case when B_Correct = 'Y' then pointsB else 0 end)
as TotalPoints
FROM Results
WHERE userID = 1
and weekID < 10
GROUP BY weekID
ORDER BY weekID ASC;