sql-max id的

busg9geu  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(343)

我有一张这样的table,

| id | name | subtask | maintask |
|----|------|---------|----------|
| 1  | t1   | 11      | 20       |
| 1  | t1   | 12      | 20       |
| 1  | t1   | 1       | 30       |
| 2  | t1   | 2       | 20       |
| 2  | t1   | 2       | 20       |

我想准备一个这样的结果

| id | name | sum_of_subtask | sum_of_maintask | diff |
|----|------|----------------|-----------------|------|
| 2  | t1   | 4              | 40              | 36   |

需要选择max id,然后对子任务和主任务求和,最后一列是sum(子任务)和sum(主任务)的差
我在下面尝试了这个查询,但它是在计算所有列的总和。

select max(id), name, sum(subtask),sum(maintask),sum(subtask-maintask) from tbl
group by name
vfh0ocws

vfh0ocws1#

select id, name, sum(subtask), sum(maintask), sum(subtask-maintask)
from tbl
where id = (select max(id) from tbl)
group by id, name
8xiog9wr

8xiog9wr2#

你只想要一排吗?如果是,请使用 order by 以及 limit :

select id, name, sum(subtask), sum(maintask), sum(subtask-maintask)
from tbl
group by id, name
order by id desc
limit 1;

如果您的数据很大,在聚合之前进行筛选可能会更有效:

select id, name, sum(subtask), sum(maintask), sum(subtask-maintask)
from tbl
where id = (select max(id) from tbl)
group by id, name;

如果你想要最大的 idname ,则过滤逻辑为:

select id, name, sum(subtask), sum(maintask), sum(subtask-maintask)
from tbl t
where t.id = (select max(t2.id) from tbl t2 where t2.name = t.name)
group by id, name;
mqxuamgl

mqxuamgl3#

请使用下面的查询,

select id, name, sum(subtask), sum (maintask), sum(subtask)-sum (maintask)
where id in
(select max(id) from table)
group by id, name;

相关问题