Here’s a challenge for a good MySQL coder.
We would greatly appreciate some help on a query to create a MySQL report displayed in an html/PHP page.
We know how to collect the data and store it, and have the PHP report layout, but are lost as to how to structure the query.
We have two MySQL tables – “visitors” and “buyers”.
- Visitors table – for visitors to our website coming in through a
particular URL which identifies the sales_rep and one of many
marketing codes they create themselves. - Buyers table – for those who buy something.
A visitor may visit our website through the following link, for example:
www.sales_rep.website.com/index.php?marketing=code1/code2/code3
In the “visitors” table we include three fields:
- sales_rep
- date
- marketing_CODE – (which in this case would be the “code1/code2/code3” in a string, but each sales_rep could have several marketing_CODES based on their advertising activities; such as “code1a/codeTX/codeM2” and “market-z/ad-123”)
When a visitor buys something, we add them to a “buyers” table, which includes:
- sales_rep
- date
- marketing_TYPE – (which can be “URL”, “referral”, or some other type)
- marketing_VALUE – (which will the marketing_CODE if the marketing_TYPE is URL)
We need to see a report for each specific sales rep, for any specified month, sorted by marketing code, only for marketing_TYPE == “URL”.
This report needs to show a week-by-week breakdown of visitors and buyers activities for each marketing_CODE, as follows:

To ensure clarity, in the above table, in WEEK 1, 8 Visitors came into the website through a link with “code1/code2/”, and 5 of them purchased something.
We’ve attempted to begin our query with the following, but don’t know where to go with it:
$chosen_month = $_POST['chosen_month'];SELECT * FROM visitors INNER JOIN buyers ON sales_rep WHERE marketing_type = "URL" AND sales_rep = '$sales_rep' AND date('Y-m') = $'chosen_month' ;- Using a while statement, we would generate the table cells for each of the records found. Using this, we know how to list every record, but we can’t figure out how display non-distinct records once, display their count, then display distinct records.
Thank you for your time and help.
Here’s my suggestion for your query.
First of all, I needed to find out the week number based on the date field so I used the answer in this question:
I’ll refer to the the result of the above as @week from now on to make things more readable 🙂
Then, I started out with just one of the tables, trying to see how many visitors a sales rep got in each month:
Now that we got this info, we’ll use the same for buyers and then join the results of these two subqueries as follows:
This should be what you’re looking for!
Here’s the same code as above updated for your situation: