gpt4 book ai didi

php - SELECT COUNT() 在左连接表 mysql 中

转载 作者:行者123 更新时间:2023-11-29 12:35:29 25 4
gpt4 key购买 nike

我正在尝试计算任何给定月份的新潜在客户数量和已关闭潜在客户数量。下面的查询正确返回月份数组,但如果该月份中有任何潜在客户或成交,则仅计数 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而责备我。这个项目一完成我就会把它扔掉。

最佳答案

构建 JOIN 的方式条件下,您只能从 MONTH(contacts.lead_date) 的记录中获得结果=MONTH(contacts.close_date)

为了解决这个问题并获得实际的计数,我建议将语句分成两个查询:

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 更好,你是对的:-)

关于php - SELECT COUNT() 在左连接表 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26848939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com