有没有办法从查询中存储一个值,然后在下面的下一个查询中使用它?

时间:2017-05-04 10:11:55

标签: database postgresql

我有一个Postgres SQL数据库,其中包含quizes,问题,答案和标记(多个表)我试图编写一个查询来计算一个测验的maxscore,然后使用刚刚计算的查询更新测验表最高分

继承我的疑惑

SELECT SUM( maxscore)
FROM (
  SELECT max(answer.answermark) AS maxscore
  FROM answer, questions
  WHERE questions.quizid = 1 AND answer.questionid = questions.questionid
  GROUP BY answer.questionid
) scr;

UPDATE quiz
SET maxscore = '50'
WHERE quizid = 1

其中" SET maxscore = '50'"我需要而不是键入50我需要使用上面的查询计算,有什么办法?

由于

2 个答案:

答案 0 :(得分:0)

尝试使用cte:

with v as (
SELECT SUM( maxscore)
FROM (
  SELECT max(answer.answermark) AS maxscore
  FROM answer, questions
  WHERE questions.quizid = 1 AND answer.questionid = questions.questionid
  GROUP BY answer.questionid
)
UPDATE quiz
SET maxscore = v.sum
from v
WHERE quizid = 1

答案 1 :(得分:0)

在这种情况下,您不需要保持状态。在spring.application.name=moduleX spring.sleuth.sampler.percentage=0.2 spring.zipkin.base-url=http://localhost:9412 子句中执行:

from

如果您想对所有update quiz set maxscore = scr.maxscore from ( select sum(maxscore) as maxscore from ( select max(a.answermark) as maxscore from answer a inner join questions q using (questionid) where q.quizid = 1 group by questionid ) s ) scr where quizid = 1 执行此操作:

quizid