1

Here I have have a table

expenses

with columns

  • id (PK)
  • type_id (FK)
  • amount
  • date
  • vehicle_id (FK)

In my jtable I want to show it like this enter image description here

I used this sql code the

SELECT vehicle_id,SUM(amount) FROM expenses GROUP BY type_id;

And I got output as

enter image description here

But I want it like previous image (the long one).. What can I do to this ?

Note

Here I used Sum for get multiple amount values.type_id used to denote various expenses type like diesel, oil, service..

4
  • how did your second picture become the output of that select statement which only returns 2 columns ? Commented Oct 15, 2015 at 16:46
  • I don't know. When I do it Navicat, it also shows the same output. Any thing wrong ? Commented Oct 15, 2015 at 16:49
  • Since it's more SQL question than Java or UI I would advise to add sql tag to list of tags. About question: did you consider using left joins in your SQL query? Commented Oct 15, 2015 at 16:50
  • No. I have no idea about it..Can't we get it from a SELECT query.. Commented Oct 15, 2015 at 16:53

1 Answer 1

1

You can do it using conditional aggregation:

SELECT vehicle_id, 
       SUM(CASE WHEN type_id = 1 THEN amount ELSE 0 END) AS Diesel,
       SUM(CASE WHEN type_id = 2 THEN amount ELSE 0 END) AS Insurance,
       SUM(CASE WHEN type_id = 3 THEN amount ELSE 0 END) AS Tyre,
       SUM(CASE WHEN type_id = 4 THEN amount ELSE 0 END) AS Battery,
       SUM(CASE WHEN type_id = 5 THEN amount ELSE 0 END) AS Oil,
       SUM(CASE WHEN type_id = 6 THEN amount ELSE 0 END) AS Garage
FROM expenses 
GROUP BY vehicle_id;

You need to GROUP BY only vehicle_id. Then perform conditional SUM operations depending on type_id. This way you can get partial sums for type_id per vehicle_id.

Demo here

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

1 Comment

thank you very much..It works nicely..I fed up with this since 5 days..thank you very much again..

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.