如何 select 最大id的记录并对值求和?
How to select the record with max id and sum the values?
我在 SQL 服务器中有以下 table:
category consumption total id
-----------------------------------
A 40 100 1
A 60 200 2
B 60 100 6
B 40 200 7
C 10 50 3
预期输出:
consumption total
------------------
100 400
逻辑:
- 仅选择类别 - A、B
- 如果在类别 A、B 中有多个记录可用。选择一个具有 MAX id 的记录
- 将消耗量和总计相加并显示结果
类别A,有2条记录可用:选择ID为MAX的记录。
在本例中,MAX id = 2. consumption = 60, total = 200
类别 B,有 2 条记录可用:选择具有 MAX id 的记录。
在本例中,MAX id = 7. consumption = 40, total = 200
输出将是消耗和总量的总和。
我能够为一个类别起草以下查询,但如何获得另一个类别和总和:
Select
s.consumption, s.total, s.rn
From
(select
consumption, total
row_number() over (partition by category order by id desc) as rn
from
[dbo].[Table_1]
where
category = ‘A’) as s
where
s.rn = 1
我认为你过于复杂了。
试试这个
select s.consumption,s.total,s.category
from
table s
where id in
(select max(Id) as id from table group by category)
and category in ('A','B') -- Or any other conditions
子查询returns
- 2
- 7
- 3
因此,只需获取与这些 ID 号相关联的值
使用 row_number() window 函数 return 具有类别和聚合最大 id 的行:
select sum(t.consumption), sum(t.total)
from (
select *, row_number() over (partition by category order by id desc) as rn
from [dbo].[Table_1]
where category in ('A', 'B')
) t
where t.rn = 1
我在 SQL 服务器中有以下 table:
category consumption total id
-----------------------------------
A 40 100 1
A 60 200 2
B 60 100 6
B 40 200 7
C 10 50 3
预期输出:
consumption total
------------------
100 400
逻辑:
- 仅选择类别 - A、B
- 如果在类别 A、B 中有多个记录可用。选择一个具有 MAX id 的记录
- 将消耗量和总计相加并显示结果
类别A,有2条记录可用:选择ID为MAX的记录。 在本例中,MAX id = 2. consumption = 60, total = 200
类别 B,有 2 条记录可用:选择具有 MAX id 的记录。 在本例中,MAX id = 7. consumption = 40, total = 200
输出将是消耗和总量的总和。
我能够为一个类别起草以下查询,但如何获得另一个类别和总和:
Select
s.consumption, s.total, s.rn
From
(select
consumption, total
row_number() over (partition by category order by id desc) as rn
from
[dbo].[Table_1]
where
category = ‘A’) as s
where
s.rn = 1
我认为你过于复杂了。
试试这个
select s.consumption,s.total,s.category
from
table s
where id in
(select max(Id) as id from table group by category)
and category in ('A','B') -- Or any other conditions
子查询returns
- 2
- 7
- 3
因此,只需获取与这些 ID 号相关联的值
使用 row_number() window 函数 return 具有类别和聚合最大 id 的行:
select sum(t.consumption), sum(t.total)
from (
select *, row_number() over (partition by category order by id desc) as rn
from [dbo].[Table_1]
where category in ('A', 'B')
) t
where t.rn = 1