12

I have the following table:

Bank:
name  val   amount
John   1     2000
Peter  1     1999
Peter  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

2 Answers 2

34
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
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick. I tried using Group by without the SUM and it didn't work. I see now that you could have the same name, with many different values under the columns amountVal1/2. Therefore I assume the group by name wouldn't know what to do with the numbers. In this case, we need to tell it to SUM them! Thanks for the help
3

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

3 Comments

Thanks I think this would work also, but I don't want to create a temporary table if possible.
@Roger: This will not create any temporary table. In some cases, it may even be faster than the GROUP BY - CASE approach.
But this will show different results if there are persons with rows only for val=1 or val=2. Or with more than one row with same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.