Ivy Professional School
Rating
Learning/SQL Data Drill #17

Yearly Product Sales Report

Last updated

Calculate yearly sales amount for each product when sales periods may start and end across different years.

SQLIntermediateDate FunctionsCASE WHENDATEDIFFYEARUNIONJOINSales Analysis

Your Objective

Calculate yearly sales amount for each product when sales periods may start and end across different years.

The Setup

Your dataset contains two sales analysis tables: 1. A Product table with product IDs and product names 2. A Sales table with product sales periods and average daily sales amount Prepare a yearly sales report for all products between 2018 and 2020 based on the number of applicable sales days.

Table Schema

Product
ColumnTypeKey / Notes
product_idINTPK
product_nameVARCHAR(255)
Sales
ColumnTypeKey / Notes
product_idINTPK, FK
period_startDATE
period_endDATE
average_daily_salesINT

Sample Data

Product — 5 rows

product_idproduct_name
1Mouse
2Keyboard
3Ram
4Processor
5Graphic Card

Sales — 10 rows

product_idperiod_startperiod_endaverage_daily_sales
12018-11-152019-01-15120
22019-03-012019-03-3180
52020-01-012020-12-315
42018-07-012018-12-3170
32019-06-152020-01-15120
12020-02-012020-06-30120
22020-07-012020-12-3180
32019-08-012019-12-3145
42019-01-012019-06-3025
52018-10-012019-03-3115

Your Task

Yearly Product Sales Report: What is the total sales amount of each product for each year based on the number of applicable sales days? The sales years are between 2018 and 2020. The final result table should have product_id, product_name, report_year, and total_amount columns.

Your output should look like this (partial example):

product_idproduct_namereport_yeartotal_amount
1Mouse20185640
1Mouse20191800
1Mouse202018120

Before You Solve

  • →Create one reporting row per product for each year from 2018 to 2020.
  • →Use CASE WHEN to calculate how many days of each sales period fall inside the reporting year.
  • →Remember that DATEDIFF returns the gap between dates, so add 1 when you need inclusive day counts.
  • →Filter out product-year combinations where the calculated amount is 0.
Explore Enterprise Solutions