This reporting exercise links sales rows to sales agents, then combines JOINs with GROUP BY, SUM() and date filters to calculate daily totals and commissions.
The weekly example uses YEARWEEK(date, 3) so the year is part of the comparison; comparing week numbers alone can mix the same week number from different years.
plus2_agent
agent_id
Autoincrement ID field, Unique id of the user / agent
coms
float with 2 decimal places, Commission of the user / agent
name
varchar(25) Name of the user / agent
email
varchar(30) Email address of the user / agent
address
varchar(30) Address of the user / agent
plus2_sales
sales_id
Autoincrement ID field, Unique id of the sales
agent_id
integer , id of the user / agent for the sale
dt_sale
Date field, Date of the sale ( can take multiple values of same date )
p_id
integer , id of the product ( can be linked to product table , future )
quantity
integer, number of product sold in the sale
total
Integer , based on this value commission will be calculated for the user / agent
Download the SQL dump of tables with sample rows to execute these queries at the end of this page.
All sales in the order of Date ( starting from recent date )
SELECT * FROMplus2_salesORDERBYdt_salesDESC
Some records are shown here ( not all )
sales_id
agent_id
dt_sales
p_id
quantity
total
1
2
2021-06-07
8
2
492
2
1
2021-06-07
7
4
408
3
4
2021-06-07
5
5
492
4
1
2021-06-07
1
4
598
5
1
2021-06-06
5
2
406
Total sales date wise using GROUP BY and in the ORDER of most recent date.
Total commission for the current date and the previous four calendar days ( use a fresh copy of sample sql dump below ) , more about CURDATE() and Date calculations here.
The following SQL dump is created dynamically by using todays date and random numbers. While using queries having CURDATE() will return different results based on the date of run of the query. So always use a fresh copy of this SQL dump to check all these queries.
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.