views:

43

answers:

2

Hello Everyone! I've got confused at the moment.

I've got one database to developed for MLM (Multi level marketing) company. so, there's one Members database.. each member have unique ID called membercode.. and all members can members under them.. can make 2 members down to 1 member.. all members are added in same table named "tbMembers" and for each member there's a "parentID" where I add member's membercode under whome that member is?.. right?

Now what's the matter is .. I want a SQL Query which can go under and under.. like 'John Doe' having two members under him named 'Suzan' and 'Ellie' and 'Suzan' is also having 2 members under her.. and same for Ellie. and for example.. 'John Doe' having about 300 members in his down line? All members are making transactions.. like they purchase product and Invoices are being generated (invoices tables have 'memberID'). Now the query is how to generate query which can calculate John Doe's Downline's TurnOver from invoices table's 'totalAmount' field's SUM?

I'm using Asp.net 2.0 (VB.net) and use SQL Server 2005 Express. How to do it? Please help me out guyz.

+1  A: 

You can use a Recursive Common Table Expression to get all descendants then join the results onto the invoices table. Something like the following.

;WITH Members AS
     ( SELECT membercode,
             parentID
     FROM    tbMembers
     WHERE   name = 'John Doe' /*Obviously Id would be better*/

     UNION ALL

     SELECT c.membercode,
            c.parentID
     FROM   tbMembers c
            JOIN Members m
            ON     m.membercode= c.parentID
     )


SELECT SUM(totalAmount) AS Amount
FROM   invoices i
       JOIN Members m
       ON     i.MemberId = m.membercode
Martin Smith
Thanks Martin, Its working great, thats what I wanted really :) Thank you guyz, Thanks a lot.. You saved my life :)
idleMind
Personally, I find it easier to visually determine the scope of a statement, CTE,etc by putting a semicolon at the *end* of the statement (every statement). What's the idea behind putting it at the start?
onedaywhen
@oneday - SQL Server is pretty lenient about not requiring semi colons so most people don't routinely include them but the one place where there are absolutely required is before the `WITH` in a CTE.
Martin Smith
"most people don't routinely include them" -- I'm not convinced of that, nor that your style is best practise. Just a matter of taste, I guess :)
onedaywhen
@oneday - From TSQL code posted on here I rarely see optional semicolons included. And at least by including it myself I pre-empt a possible complaint that it doesn't work and gives an "Incorrect syntax" error!
Martin Smith
A: 

I think you need to use recursive user defined function. Which will calculate the total sum.

jalpesh
Thanks Martin, Its working great, thats what I wanted really :)Thank you guyz, Thanks a lot.. You saved my life :)
idleMind