SQL通过多个id对多个列进行求和

时间:2017-07-18 09:05:02

标签: sql sum firebird

我想用多列和ids对表进行求和。

我的表(两个表的连接)如下所示:

unique_ID, year, ID1, Amount1, ID2, Amount2, ID3, Amount3, ... , ID6, Amount6;

我需要获取ID与(Amount1+Amount2+...+Amount6)匹配的金额(ID1=ID2=...=ID6)的总和。

所以结果表看起来像这样: Year, ID1(/ID2/.../ID6), Amount1 + ... + Amount6

示例数据:(由excel制作)

Source table                                    
UID     YEAR    ROOM1       AMOUNT1 ROOM2       AMOUNT2
15823   2015    Material1   1       Material3   8
15298   2015    Material1   2       Material3   9
22405   2015    Material2   3       Material4   10
22403   2015    Material2   4       Material5   11
22404   2015    Material2   5       Material5   12
25417   2016    Material1   6                   0
31435   2016    Material2   7       Material2   13

Result table        
YEAR    Material    AMOUNT
2015    Material1   3
2015    Material2   12
2015    Material3   17
2015    Material4   10
2015    Material5   23
2016    Material1   6
2016    Material2   20

说明: 我有一个带产品的大桌子,每个产品最多可以包含6种原材料。 (ID 1-6标识材料,金额1-6表示使用的材料量)。材料的顺序可以变化。 我需要按年份和材料了解所用材料的数量。

我有半解决方案,需要在excel中进行大量的后续工作。 在SQL中有没有简单而优雅的解决方案?

我正在使用Firebird,但任何帮助都会受到赞赏。

提前致谢!

1 个答案:

答案 0 :(得分:2)

您似乎想要每年的总金额和材料。因此,首先获得适当的材料/年表,然后聚合:

select 
  year,
  material_id,
  sum(amount) as total
from
(
  select year, id1 as material_id, amount1 as amount from mytable
  union all
  select year, id2 as material_id, amount2 as amount from mytable
  union all
  select year, id3 as material_id, amount3 as amount from mytable
  union all
  select year, id4 as material_id, amount4 as amount from mytable
  union all
  select year, id5 as material_id, amount5 as amount from mytable
  union all
  select year, id6 as material_id, amount6 as amount from mytable
) materials
where material_id is not null
group by year, material_id
order by year, material_id;