开发者

SQL query to pivot a column using CASE WHEN

I have the following table:

Bank:
name  val   amount
John   1     2000
Peter  1     1999
Pete开发者_如何学Cr  2     1854
John   2     1888

I am trying to write an SQL query to give the following result:

name  amountVal1 amountVal2  
John    2000        1888   
Peter   1999        1854    

So far I have this:

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

However, it gives the slightly wrong result:

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

How can I modify my query to give the correct presentation? Thanks


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


Looks like you need to join the table on itself. Try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜