我有这个查询,我得到一些列的计数我的问题是计算所有这些计数结果在一个新的领域
SELECT
CONCAT(u.firstname,' ',u.lastname) AS 'agent',
COUNT(CASE WHEN pa.answer_text LIKE '%yes%' THEN pa.answer_id END) AS yes,
COUNT(CASE WHEN pa.answer_text LIKE '%no%' THEN pa.answer_id END) AS NO,
COUNT(CASE WHEN l2u.lead_status_id IN (4,5,8,39) THEN l2u.lead_id END) AS pending,
COUNT(CASE WHEN l2u.lead_status_id IN (7,14,43) THEN l2u.lead_id END) AS wrong_number,
这是问题..这个的正确语法是什么 COUNT(待定+错误编号+是+否)AS'总计'
FROM USER u, poll_votes pv, poll_answers pa, lead_to_user_original l2u
WHERE u.user_id = pv.user_id
AND pv.answer_id = pa.answer_id
AND l2u.lead_id = pv.vote_lead_id
AND (pa.answer_client_one = '869' OR pa.answer_client_two = '869')
AND pv.vote_date BETWEEN '2013-07-01 00:00:01' AND '2013-07-17 23:59:59'
GROUP BY u.user_id
答案 0 :(得分:2)
如何将它包装在子查询中?
SELECT agent, yes, no, pending, wrong_number,
yes + no + pending + wrong_number AS Total
FROM
(
SELECT CONCAT(u.firstname,' ',u.lastname) AS 'agent',
COUNT(CASE WHEN pa.answer_text LIKE '%yes%' THEN pa.answer_id END) AS yes,
COUNT(CASE WHEN pa.answer_text LIKE '%no%' THEN pa.answer_id END) AS NO,
COUNT(CASE WHEN l2u.lead_status_id IN (4,5,8,39) THEN l2u.lead_id END) AS pending,
COUNT(CASE WHEN l2u.lead_status_id IN (7,14,43) THEN l2u.lead_id END) AS wrong_number
FROM USER u
INNER JOIN poll_votes pv
ON u.user_id = pv.user_id
INNER JOIN poll_answers pa
ON pv.answer_id = pa.answer_id
INNER JOIN lead_to_user_original l2u
ON l2u.lead_id = pv.vote_lead_id
WHERE (pa.answer_client_one = '869' OR pa.answer_client_two = '869')
AND pv.vote_date BETWEEN '2013-07-01 00:00:01' AND '2013-07-17 23:59:59'
GROUP BY u.user_id
) subA
答案 1 :(得分:2)
您无法在select中的另一个字段中的SELECT
子句中访问别名。您可以将其“推送”到子查询,并执行以下操作:
SELECT a.*, pending + wrong_number + yes + no AS 'total'
FROM (
SELECT
CONCAT(u.firstname,' ',u.lastname) AS 'agent',
COUNT(CASE WHEN pa.answer_text LIKE '%yes%' THEN pa.answer_id END) AS yes,
COUNT(CASE WHEN pa.answer_text LIKE '%no%' THEN pa.answer_id END) AS NO,
COUNT(CASE WHEN l2u.lead_status_id IN (4,5,8,39) THEN l2u.lead_id END) AS pending,
COUNT(CASE WHEN l2u.lead_status_id IN (7,14,43) THEN l2u.lead_id END) AS wrong_number,
FROM USER u
JOIN poll_votes pv
ON u.user_id = pv.user_id
JOIN poll_answers pa
ON pv.answer_id = pa.answer_id
JOIN lead_to_user_original l2u
ON l2u.lead_id = pv.vote_lead_id
WHERE (pa.answer_client_one = '869' OR pa.answer_client_two = '869')
AND pv.vote_date BETWEEN '2013-07-01 00:00:01' AND '2013-07-17 23:59:59'
GROUP BY u.user_id
) AS a
我还将您的查询更改为使用"ANSI-92 style" joins,我认为它更具可读性......