[英]Select the sum of a column and value of the last column together in a SQL query
I have a table named results where I have id(pk) and marks.我有一个名为 results 的表,其中包含 id(pk) 和标记。 I want to develop a select query to get the sum(marks) and also the highest individual marks in a single query.
我想开发一个选择查询来获取总和(标记)以及单个查询中最高的单个标记。 Is it possible?
是否可以?
sample data:样本数据:
Expected output: Sum(224), last_marks(44)预期输出:Sum(224),last_marks(44)
I have tried the following way:我尝试了以下方法:
SELECT SUM(marks), latest.marks
FROM results
JOIN ( SELECT marks FROM results ORDER BY id DESC LIMIT 1) as latest;
It shows error as follows: Error Code: 1052. Column 'marks' in field list is ambiguous它显示如下错误:错误代码:1052。字段列表中的列“标记”不明确
You can get result using seperate queries and merging results using UNION
.您可以使用单独的查询获得结果,并使用
UNION
合并结果。
SELECT SUM(marks) AS marks_sum FROM results
UNION
SELECT marks AS latest_marks FROM results WHERE id=(SELECT MAX(id) FROM results)
OR if need results in one row use query in query:或者,如果需要在一行中使用查询结果:
SELECT (SELECT SUM(marks) FROM results) AS marks_sum,
(SELECT marks FROM results WHERE id=(SELECT MAX(id) FROM results)) AS latest_marks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.