我不会得到非零的funnel_id计数。我得到funnel_id计数,但也显示funnel_id的计数为零,在这里我们不添加where子句,在此查询中我也得到page_count。
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
`page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct(page_pages.funnel_id) )as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE smart_projects.status != 0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
AND `smart_projects`.`created_date` BETWEEN 1558031400 AND 1558722600
GROUP BY `smart_projects`.`project_id`
ORDER BY `funnel_count` ASC
LIMIT 10
page_pages表为:
smart_projects表为:
结果是:-
预期结果是:
答案 0 :(得分:0)
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
`page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE smart_projects.status != 0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC
答案 1 :(得分:-1)
如果要过滤出零值,请使用having
子句:
SELECT sp.project_id, sp.business_id, sp.title,
count(distinct pp.page_id ) as page_count,
count(distinct pp.funnel_id ) as funnel_count
FROM `smart_projects` sp LEFT JOIN
`page_pages` pp
ON sp.`project_id` = pp.`project_id`
WHERE sp.status <> 0 AND
sp.`business_id` = 'cd9412774edb11e9' AND
sp.`created_date` BETWEEN 1558031400 AND 1558722600
GROUP BY sp.`project_id`
HAVING funnel_count > 0
ORDER BY `funnel_count` ASC
LIMIT 10;
注意:
DISTINCT
不是函数,而是关键字。以下表达式不需要括号。funnel_id
在SELECT
中不合适,因为它是聚合函数的参数。