简体   繁体   English

按多个条件对MySQL查询结果进行分组

[英]Group MySQL query result by more than one criteria

I have a simple referrers table with three columns: 我有一个包含三列的简单referrers表:

Referrer    //string name of partner
TimeOfVisit //timestamp
SessionID   //(unique id only used when joining with sales data for conversion)

I would like to retrieve data for analytics, and present a stacked column chart, with a column for each day showing the referrer sources for visitors. 我想检索数据进行分析,并显示一个堆积的柱状图,每天都有一列显示访问者的引荐来源。

This is the query that I managed to put together: 这是我设法整理的查询:

SELECT
    DATE(TimeOfVisit) AS Date,
    Referrer,
    COUNT(Referrer) AS VisitorCount
FROM referrers
GROUP BY CONCAT(DATE(time_of_visit), referrer)

It does kind of give me the data I am looking for: 它确实可以为我提供所需的数据:

Array
(
    [0] => Array
        (
            [Date] => 2012-04-01
            [Referrer] => adwords
            [VisitorCount] => 3
        )

    [1] => Array
        (
            [Date] => 2012-04-01
            [Referrer] => facebook
            [VisitorCount] => 5
        )

    [2] => Array
        (
            [Date] => 2012-04-02
            [Referrer] => adwords
            [VisitorCount] => 6
        )
...

I have two problems with this: 我对此有两个问题:

  1. Even I can feel it, that grouping by a concatenated string is hideous, it just does not feel right. 即使我能感觉到,按连接的字符串分组也是令人毛骨悚然的,只是感觉不对。
  2. The php script parsing the result will always need to know the full list of current referrers, so it can assign a 0 value in case there were no clicks from a refferer on a given day. 解析结果的php脚本将始终需要知道当前引荐来源网址的完整列表,因此,如果给定日期没有来自推荐人的点击,则可以将其分配为0值。 Not very elegant, to say the least. 至少可以说不是很优雅。

What is the most effective way to solve this problem? 解决此问题的最有效方法是什么? Could it actually be solved in MySQL only? 难道只能在MySQL中解决?

You can just GROUP BY Date, Referrer 您可以按推荐人GROUP BY Date, Referrer

The MySQL results will have "gaps", periods in which certain referrers will have 0 hits. MySQL的结果将带有“空白”,在此期间某些引荐来源网址的匹配数为0。

Assuming you're colouring the referrers (not sure how many you have) and you wish to have a consistent colour for each, you could calculate a numeric hash and use that as an index over a predefined array of colours. 假设您正在为引荐来源网址上色(不确定您有多少个引荐网址),并且希望为每个引荐网址都具有一致的颜色,则可以计算数字哈希并将其用作预定义颜色数组的索引。

Not sure whether I've addressed all your questions or if you understood all of my answer, but just shout :) 不知道我是否已经解决了您所有的问题,或者您是否理解我所有的答案,只是大喊一声:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM