我有以下查询,我正在尝试生成四列,买方, 来源,潜在客户总数和退回的潜在客户。
问题在于包含一个包含总线数的列。返回是我的数据库中的一个列,其中值为0或1.所以返回的是1的所有内容,但对于已购买的潜在客户,我需要的所有内容为0.当我运行以下查询时,所有购买的潜在客户最终都是0.如何修复子查询以获得所需的结果。
SELECT
ba.buyer,
l.source,
(SELECT COUNT(*) FROM lead_status WHERE lead_id = l.id AND returned != 1) AS 'Bought Leads',
SUM(l.returned) AS 'Returned_Leads'
FROM lead_status AS ls
LEFT JOIN leads AS l ON ls.lead_id = l.id
LEFT JOIN buyer_account AS ba ON ba.lead_buyer_id = ls.lead_buyer_id
WHERE l.origin = 'PING_POST'
AND ls.discriminator IN('AUTO_POST','HOME_POST','HEALTH_POST','LIFE_POST')
AND DATE(ls.create_date) BETWEEN '2012-02-01' AND '2012-02-31'
AND l.sold = 1 AND ls.winner = 1 AND l.test = 0 AND l.returned = 1
GROUP BY ls.buyer, l.source;
答案 0 :(得分:3)
只需将子查询替换为:
SUM(1-l.returned)
只要它是一个位字段,否则你应该使两个和操作CASE语句,即sum(在0时返回的情况,然后在0结束时返回)。
答案 1 :(得分:1)
尝试
SUM( abs(l.returned-1) )
取abs()值会得到+1,所以你的SUM()应该可以工作
答案 2 :(得分:1)
我认为你可以做一个替代方案,如果它是二进制1或0:
SELECT
ba.buyer,
l.source,
COUNT(l.returned) - SUM(l.returned) AS 'Bought Leads',
SUM(l.returned) AS 'Returned_Leads'
FROM lead_status AS ls
LEFT JOIN leads AS l ON ls.lead_id = l.id
LEFT JOIN buyer_account AS ba ON ba.lead_buyer_id = ls.lead_buyer_id
WHERE l.origin = 'PING_POST'
AND ls.discriminator IN('AUTO_POST','HOME_POST','HEALTH_POST','LIFE_POST')
AND DATE(ls.create_date) BETWEEN '2012-02-01' AND '2012-02-31'
AND l.sold = 1 AND ls.winner = 1 AND l.test = 0 AND l.returned = 1
GROUP BY ls.buyer, l.source;