我有以下查询。如何使用“ spendamount”,“ winamount” 在2个查询的结果之间进行减法。当我减去(spendamount-winamount)时,出现以下错误:
1054-“字段列表”中的未知列“ spendamount”
SELECT tbl_customers.*,
IFNULL((SELECT sum(win_amount) FROM `tbl_cricket_customer_contests` where customer_id=tbl_customers.id), 0) as winamount,
(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,
(spendamount-winamount)
FROM (`tbl_customers`)
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
答案 0 :(得分:2)
请重写查询,以使用联接获取总数量:
SELECT t.*,
COALESCE(c.win_amount, 0) AS winamount,
COALESCE(tccc.amount, 0) AS spendamount,
(COALESCE(tccc.amount, 0) - COALESCE(c.win_amount, 0)) AS diff
FROM tbl_customers t
LEFT JOIN
(
SELECT customer_id, SUM(win_amount) AS win_amount
FROM tbl_cricket_customer_contests
GROUP BY customer_id
) c
ON c.customer_id = t.id
LEFT JOIN
(
SELECT customer_id, SUM(tcc.entry_fees) as amount
FROM tbl_cricket_customer_contests tccc
INNER JOIN tbl_cricket_contest_matches tccm
ON tccm.id = tccc.match_contest_id
INNER JOIN tbl_cricket_contests tcc
ON tcc.id = tccm.contest_id
) tccc
ON tccc.customer_id = t.id
WHERE
t.is_deleted = 'N'
ORDER BY
spendamount DESC;
答案 1 :(得分:1)
使用实际表达式代替别名,也可以使用子查询
select *,spendamount-winamount from
(
SELECT tbl_customers.*,
IFNULL((SELECT sum(win_amount) FROM `tbl_cricket_customer_contests` where customer_id=tbl_customers.id), 0) as winamount,
(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'
)A
答案 2 :(得分:1)
请尝试此查询。
SELECT AA.*,AA.spendamount - AA.winamount As Amount FROM
(
SELECT tbl_customers.*,
IFNULL((SELECT sum(win_amount) FROM `tbl_cricket_customer_contests` where customer_id=tbl_customers.id), 0) as winamount,
(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,
(spendamount-winamount)
FROM (`tbl_customers`)
WHERE `tbl_customers`.`is_deleted` = 'N'
GROUP BY `tbl_customers`.`id`
ORDER BY `spendamount` DESC
)As AA