When us table customer id than getting error
#1054 - Unknown column 'tbl_customers.id' in 'where clause'
Actually problems is Every derived table must have its own alias.
Like this query following.
SELECT tbl_customers.*,(SELECT SUM(amount) As Amount
FROM
(
SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount
FROM `tbl_cricket_customer_contests` tccc
LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id)
LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id)
WHERE tccc.customer_id = tbl_customers.id GROUP BY tccc.match_contest_id
) As DT) as spendamount
FROM (`tbl_customers`)
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
Below table relationship structure following this in query.
You where using tbl_customers on the subquery where you didnt had access to it. You just had to join instead of using where:
SELECT tbl_customers.*,(SELECT SUM(amount) As Amount
FROM
(
SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount
FROM `tbl_cricket_customer_contests` tccc
JOIN `tbl_customers` ON (tccc.customer_id = tbl_customers.id)
LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id)
LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id)
GROUP BY tccc.match_contest_id
) As DT) as spendamount
FROM (`tbl_customers`)
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
I'm not sure this will work for MySql, but try to move the derived table from the subquery to the from
clause (Note: I've changed the group by column of the derived table, but I think it should be O.K in this case):
SELECT tbl_customers.*,(SELECT SUM(amount) As FROM DT) as spendamount
FROM `tbl_customers`
INNER JOIN
(
SELECT tccc.customer_id, tcc.entry_fees * COUNT(tccc.match_contest_id) as amount
FROM `tbl_cricket_customer_contests` tccc
LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id)
LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id)
GROUP BY tccc.customer_id
) As DT
ON dt.customer_id = `tbl_customers`.`id`
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
If I want the total amount, don't nest the aggregation functions and remove the group by:
SELECT tbl_customers.*,(SELECT SUM(tcc.entry_fees) as amount
FROM tbl_cricket_customer_contests tccc
JOIN tbl_cricket_contest_matches tccm ON tccm.id = tccc.match_contest_id
JOIN tbl_cricket_contests tcc ON tcc.id = tccm.contest_id
WHERE tccc.customer_id = tbl_customers.id ) as spendamount
FROM (`tbl_customers`)
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
I also changed the LEFT JOIN to JOIN. You are summing values from the last table, so only matching rows contribute to the sum.