0

My returned query looks like this

Name Type 1 Type 2 Type 3
John 1
John 3
John 5
Ronn 11
Ronn 9
Ronn 7

but I want them to be in a single row that looks like this, what functions should I use?

Name Type 1 Type 2 Type 3
John 1 3 5
Ronn 11 9 7

Here's my query

SELECT c.name, 
       if(t.type = A, SUM(t.amount), "") AS Type 1,
       if(t.type = B, SUM(t.amount), "") AS Type 2,
       if(t.type = C, SUM(t.amount), "") AS Type 3
FROM 
       customer AS c,
       transaction AS t,
       t_detail AS td

WHERE
       c.id = td.id
       AND t.type IN ("A", "B", "C")

GROUP BY c.id, t.type

customer

id = fk to t_details

transaction

amount
type

t_detail

t_id id = FK. customer id

2
  • Can you give sample data for your two tables? Commented Jul 12, 2021 at 14:00
  • @Kevin see edited ty Commented Jul 12, 2021 at 14:11

1 Answer 1

1

you have to provide more information ( sample data) but seems like you need to group by name:

SELECT c.name, 
       SUM(case when t.type = 'A' then t.amount end) AS Type1,
       SUM(case when t.type = 'B' then t.amount end) AS Type2,
       SUM(case when t.type = 'C' then t.amount end) AS Type3
FROM  customer AS c
inner join transaction as t
   on c.id = t.id
   AND t.type IN ("A", "B", "C")
GROUP BY c.name    

also always use explicit join.

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

4 Comments

it still return the same table
it sums up all the values and returns to 4th column(type 3)
thanks man, problem solved! Thank you. Been trying to solve this for more than an hour now, thanks
You don't actually need "AND t.type IN ("A", "B", "C")"

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.