0

I have a table like this:

user_id, gender, sent
1        M       100
1        F       120
2        M       20
2        F       30

I want a table like this from the above:

user_id, male_sent, female_sent, total_sent 
1        100        120          220 
2        20         30           50 

I lack the (Postgres) SQL foo to figure this one out.

3
  • Hi, I am using PSQL, I tagged it with psql. Commented Mar 17, 2013 at 23:15
  • Have you had a look at the tag description of psql? You are probably talking talking about PostgreSQL. Commented Mar 22, 2013 at 3:58
  • Oops, you are right. psql != postgresql Commented Mar 23, 2013 at 19:17

2 Answers 2

2

You can use an aggregate function with a CASE expression to get the result:

select user_id,
  sum(case when gender = 'M' then sent else 0 end) male_sent,
  sum(case when gender = 'F' then sent else 0 end) female_sent,
  sum(sent) total_sent
from yourtable
group by user_id

See SQL Fiddle with Demo

Sign up to request clarification or add additional context in comments.

Comments

2

What database are you using?

If you are using SQL Server, you could do something like this:

SELECT user_id,sum(case when gender = 'M' then sent else 0 end) as male_sent,
sum(case when gender = 'F' then sent else 0 end) as female_sent,
sum(sent) as total_sent
FROM your_table_name
GROUP BY user_id

Comments

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.