在mysql中排序多个COUNT个实例?

时间:2014-02-03 19:21:28

标签: mysql count

SELECT
smart_curmonth_portals.portal_name,
COUNT(smart_curmonth_portals.portal_name) as Hits,
COUNT(smart_curmonth_portals.page_name is 'Home') as Home*******
COUNT(smart_curmonth_portals.page_name is not 'Home') as Subpage*******
COUNT(smart_curmonth_portals.page_name is NULL) as Downloads*******
FROM
smart_curmonth_portals
GROUP BY
smart_curmonth_portals.portal_name
ORDER BY
Hits DESC 

我有一个表 - smart_curmonth_portals,我用它来报告用户点击数。我没有做分析报告 - 它的格式不好,所以我不能改变它。该表格如下:

  1. portal_name - 目前正在对此进行COUNT并正常工作
  2. page_name - 给出了一个人进入#1门户网站时的确切页面。大多数情况下它是'Home',有时它是一个具有随机名称的子页面,有时它是NULL并且转到#3。
  3. doctitle - #2上的NULL只是直接项目下载,每个都有名称 - 我们不需要,但我们需要计算。
  4. 想看看:

    Portal_Name   Hits   Home   Subpages    Downloads
    Testportal    3000   2300    600        100
    

2 个答案:

答案 0 :(得分:2)

COUNT(x)计算x不为空的次数。在您的查询中,它可能返回所有值的总行数(或接近它)。

如果您想要条件为真的行数,请使用sum()

SELECT scp.portal_name,
       sum(scp.portal_name) as Hits,
       sum(scp.page_name = 'Home') as Home,
       sum(scp.page_name <> 'Home') as Subpage,
       sum(scp.page_name is NULL) as Downloads
FROM smart_curmonth_portals scp
GROUP BY scp.portal_name
ORDER BY Hits DESC ;

答案 1 :(得分:1)

一般(不特定于MySQL)解决方案是:

select portal_name
    ,COUNT(portal_name) as Hits
    ,COUNT(case when page_name = 'Home' then 1 end) as Home
    ,COUNT(case when page_name <> 'Home' then 1 end) as Subpage
    ,COUNT(case when page_name is null then 1 end) as Downloads
from smart_curmonth_portals
group by portal_name
order by Hits desc