database - mysql query to get sum and count -
i using following query now...
select id, account_number, (select count(*) `member_tbl` t2 t2.referred_by = t1.account_number ) total_referred `member_tbl` t1;
and provides following result...
id - id of memenr account_number - account number of user total_referred - total number of members referred account_number
but want more results following...
total_reffered2 - total number of members they(all accounts referred account_number) referred total_reffered3 - total number of members referred members of total_reffered2
please check mysql fiddle
and per mysql fiddle data, query must return following values...
| id | account_number | referred_by1 | referred_by2 | referred_by3 +----+-----------------+---------------+--------------+------------- | 1 | ac203003 | 0 | 0 | 0 +----+-----------------+---------------+--------------+------------- | 2 | ac203004 | 1 | 1 | 0 +----+-----------------+---------------+--------------+------------- | 3 | ac203005 | 2 | 1 | 1 +----+-----------------+---------------+--------------+-------------
let me give example
if every member had 10 referrals, then...
referred_by1 = 10 referred_by2 = 100 referred_by3 = 1000
i confused, how write query?
well, can keep on same path on, using more complex queries. think want:
select id, account_number, (select count(*) `member_tbl` t2 t2.referred_by = t1.account_number ) total_referred, (select count(*) `member_tbl` t2 join member_tbl t3 on t3.referred_by = t2.account_number t2.referred_by = t1.account_number ) refer4ed_by_2, (select count(*) `member_tbl` t2 join member_tbl t3 on t3.referred_by = t2.account_number join member_tbl t4 on t4.referred_by = t3.account_number t2.referred_by = t1.account_number ) referred_by_3 `member_tbl` t1;
this doesn't match "expected" results sql fiddle. again, expected results don't have right number of rows, don't seem correct.
Comments
Post a Comment