如何从具有特定标签集的原始数据中获取金额总和

How to get sum of amounts from raw data having specific labels set

我在 sql 中有一个 table,如下所示:

Code Label Amount
X    this  100
X    this  300
X    this  500
X    last  700
X    last  800

预期输出为:

Code ThisAmount LastAmount
X    900        1500

我试过以下但没有按预期工作:

select t.code, sum(t2.amount) ThisAmount, sum(t3.amount) LastAmount
from table t
inner join table t2 on t.code=t2.code and t2.label='this'
inner join table t3 on t.code=t3.code and t2.label='last'
group by t.code

你能帮忙吗?

谢谢

您需要使用条件聚合:

select 
   t.code
   , sum(case when Label = 'this' then amount end) ThisAmount
   , sum(case when Label = 'last' then amount end) LastAmount
from table t
group by t.code