For simplicity, I have the following tables:
+transactions
- id
- user_id
- name
- date
+users
- id
+tags_transactions
- id
- transaction_id
- tag_id
+tags
- name
- id
- name
- parent_id
In the tags table, parent_id refers to another record in tags table, so tags can function as groups and subgroups. A subgroup tag will have a value for parent_id. Main tags or groups will have null for parent_id because they work as the root of a category.
Let's say I have the following tags:
+Auto
- Insurance
- Gas
- Maintenance
+Housing
- Rent
- Utilities
- etc
Now, I have a transaction and I tag it with "Gas". Transactions can have only one tag (so they can be part of only a group or a subgroup, but by being part of a subgroup, they are automatically part of a group. i.e. The transaction I just tagged with "Gas" is also part of "Auto".
I need to write a query that will help me know how much a given user spends per month per group (not subgroup, so I want the total spending per month for Auto and for Housing).
I've come up with the following query
SELECT tags.name, YEAR(t.date), MONTH(t.date), SUM(t.deposit), SUM(t.withdrawal) FROM transactions AS t
INNER JOIN users AS u
ON u.id = t.user_id
INNER JOIN tags_transactions AS tt
ON tt.transaction_id = t.id
INNER JOIN tags AS tags
ON tags.id = tt.tag_id
WHERE t.user_id = 92
GROUP BY tags.id, YEAR(t.date), MONTH(t.date);
but this gets only the spending per month for subgroups (insurance, gas, maintenance, rent, etc).
There are hundreds, if not thousands, of tags as the users create them...
Any idea on how to get the spending per month per category/group?
Any help will be appreciated!