获取列的总和而不影响三列的分组

时间:2016-11-22 04:16:34

标签: mysql group-by sum

我的查询看起来像这样;

SELECT count(visitor_city) as cnt, page_id, page_type, visitor_city, visitor_state
FROM visitors
GROUP BY page_id, page_type, visitor_city
ORDER BY cnt DESC

以上工作正常,但我也想得到每个分组的所有“计数”的总和。

我需要添加'count'的SUM。

原因是,初始查询获取页面的UNIQUE访问者,但我也想获得对页面的整体访问。 'count'列保存每个ip的多个视图。

编辑:

我没有意识到只将SUM(count)添加为..不会影响分组。

SELECT count(page_id) as cnt, page_id, page_type, visitor_city, visitor_state, SUM(count) as pv 
FROM visitors GROUP BY page_id, page_type, visitor_city 
ORDER BY cnt DESC

完成了这项工作。

1 个答案:

答案 0 :(得分:0)

Select  sum(OriginalCount.cnt), OriginalCount.page_id, OriginalCount.page_type, OriginalCount.visitor_city, OriginalCount.visitor_state
from 
(SELECT count(visitor_city) as cnt, page_id, page_type, visitor_city, visitor_state
    FROM visitors
    GROUP BY page_id, page_type, visitor_city, visitor_state
    ) as OriginalCount
group by OriginalCount.page_id, OriginalCount.page_type, OriginalCount.visitor_city, OriginalCount.visitor_state
order by 1 desc