SQL查询来使用CASE WHEN来转换列

我有下面的表格:

Bank: name val amount John 1 2000 Peter 1 1999 Peter 2 1854 John 2 1888 

我正在尝试编写一个SQL查询来给出以下结果:

 name amountVal1 amountVal2 John 2000 1888 Peter 1999 1854 

到目前为止,我有这样的:

 SELECT name, CASE WHEN val = 1 THEN amount ELSE 0 END AS amountVal1, CASE WHEN val = 2 THEN amount ELSE 0 END AS amountVal2 FROM bank 

但是,它给出了一些错误的结果:

 name amountVal1 amountVal2 John 2000 0 Peter 1999 0 John 0 1888 Peter 0 1854 

我如何修改我的查询来给出正确的演示文稿? 谢谢

 SELECT name, SUM(CASE WHEN val = 1 THEN amount ELSE 0 END) AS amountVal1, SUM(CASE WHEN val = 2 THEN amount ELSE 0 END) AS amountVal2 FROM bank GROUP BY name 

看起来你需要join表格本身。 尝试这个:

 select bank1.name, bank1.amount, bank2.amount from bank bank1 inner join bank bank2 on bank1.name = bank2.name and bank1.val = 1 and bank2.val = 2