I have a simple referrers table with three columns:
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:
- Even I can feel it, that grouping by a concatenated string is hideous, it just does not feel right.
- 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. 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?
You can just
GROUP BY Date, ReferrerThe MySQL results will have “gaps”, periods in which certain referrers will have 0 hits.
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 🙂