没有where子句的非零id计数

时间:2019-05-24 10:19:09

标签: mysql sql

我不会得到非零的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 table

smart_projects表为:

enter image description here

结果是:-

enter image description here

预期结果是:

enter image description here

2 个答案:

答案 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_idSELECT中不合适,因为它是聚合函数的参数。