我试图计算任何一个月内新线索的数量和封闭线索的数量。下面的查询正确地返回月份数组,但是如果在月份中有任何潜在客户或关闭,则只计算1,而不是在该月份发生的实际数字。我有什么想法吗?
查询:
$productSql = "SELECT months.monthnum as monthnum, COUNT(contacts.lead_date) as lead_date_month, COUNT(contacts.close_date) as close_date_month, contacts.rep as rep
FROM months
LEFT JOIN contacts
ON months.monthnum = MONTH(contacts.lead_date)
AND months.monthnum = MONTH(contacts.close_date)
AND contacts.compid='$compid'
AND YEAR(contacts.lead_date) = '$year'
AND YEAR(contacts.close_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY months.monthnum
ORDER BY months.monthnum ASC";
$productResult = mysql_query($productSql, $link) or die(mysql_error());
$label[] = $productRow['monthnum'];
$lead[] = $productRow['lead_date_month'];
$close[] = $productRow['close_date_month'];
};
echo "[".json_encode($label).",".json_encode($lead).",".json_encode($close)."]";
结果:
[["January","February","March","April","May","June","July","August","September","October","November","December"],
["0","0","0","0","0","0","0","0","1","1","0","0"],
["0","0","0","0","0","0","0","0","1","1","0","0"]]
**请不要因为使用mysql而惩罚我。这个项目完成后我立即抛弃它。
答案 0 :(得分:1)
您构建JOIN
条件的方式只会从MONTH(contacts.lead_date)
= MONTH(contacts.close_date)
的记录中获得结果。
要解决这个问题并获得实际的Count,我建议将该语句拆分为两个查询:
SELECT
a.monthnum,
a.lead_date_month, b.close_date_month,
b.close_date_month / a.lead_date_month
FROM
(
-- Count number of new leads
SELECT
months.monthnum as monthnum,
COUNT(*) as lead_date_month,
contacts.rep as rep
FROM
months
LEFT JOIN contacts
ON
months.monthnum = MONTH(contacts.lead_date)
AND contacts.compid='$compid'
AND YEAR(contacts.lead_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY
months.monthnum
ORDER BY
months.monthnum ASC
) as a
JOIN
(
-- Count number of closed leads
SELECT
months.monthnum as monthnum,
COUNT(*) as close_date_month,
contacts.rep as rep
FROM
months
LEFT JOIN contacts
ON
months.monthnum = MONTH(contacts.close_date)
AND contacts.compid='$compid'
AND YEAR(contacts.close_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY
months.monthnum
ORDER BY
months.monthnum ASC
) as b
ON a.monthnum = b.monthnum
MySQL并没有那么糟糕。但MariaDB更好,你是对的: - )