Lets say I have the following schema:
person (person_id, person_account, name)
relationships (person_id, father_id)
purchases(person_account, total, type)
Disclaimer: I did not design this schema, I know it's terrible so I apologize. Also this is an example, this is much more complicated. Also note that this is a query that I will use in JDBCTemplate, which is why I included the tag.
Now I want to get a count
of a person's purchases, and his or her sons purchases and their sons purchases and so on. I want a specific starting point on the initial person.
Couple of things that differ from the examples I've seen so far:
- A specific starting point (let's say it's
person_account
). - the table
purchases
has noperson_id
field, so it complicates things. - I want a
count
and not other stuff. - I want to filter by
type
ofpurchase
. - Since the
father_id
relationship is in another table, it would mean a join has to be made. Again it's horrible but I cannot change the database to include afather_id
field in theperson
table. - If a person has no father, there is NO entry in the
relationships
table. That will complicate it even further.
Now I've read the examples and I understand a couple of them:
How to get all children of a parent and then their children using recursion in query
SQL Server recursive query
http://msdn.microsoft.com/en-us/library/ms186243.aspx
However, I have problems understanding the starting and ending points. My starting point COULD have a father, so that cannot be null. My endpoints should get purchases
from people that have no entries on the relationships
table basically.
So what I'm thinking is:
declare @id int = 234
;with CTEexample as (
select p.person_account, p.person_id, p.type, r.father_id from purchases as s
join person p on p.person_account = s.person_account
join relationships r on r.person_id = p.person_id
where r.person_id = @id
union all
select p.person_account, p.person_id, p.type, r_father_id from purchases as s
join person p on p.person_account = s.person_account
join relationships r on r.person_id = p.person_id
join CTEexample c on p.person_id = r.father_id
)
select count(*) from CTEexample
where type = 's'
However, it isn't working at all.
Any help would be appreciated.