Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update total-sales-amount-by-year.sql #120

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Enigma62
Copy link

@Enigma62 Enigma62 commented Nov 3, 2020

this is a hard coded solution for the problem 1384. Total Sales Amount by Year (hard)

Write an SQL query to report the Total sales amount of each item for each year, with corresponding product name, product_id, product_name and report_year.
Dates of the sales years are between 2018 to 2020. Return the result table ordered by product_id and report_year.

drop table if exists #Product;

Create table #Product
(
product_id int not null,
product_name varchar(50) not null,
Constraint PK_Product_product_id Primary Key (product_id)
);

Truncate table #Product;

insert into #Product (product_id, product_name)
values
( 1 , 'LC Phone' ),
( 2 , 'LC T-Shirt' ),
( 3 , 'LC Keychain' );

select * from #Product;

drop table if exists #Sales;

Create table #Sales
(
product_id int not null,
period_start varchar(50) not null,
period_end date not null,
average_daily_sales int not null,
Constraint PK_Sales_product_id Primary Key (product_id)
);

Truncate table #Sales;

insert into #Sales (product_id , period_start , period_end , average_daily_sales)
values
( 1 , '2019-01-25' , '2019-02-28' , 100 ),
( 2 , '2018-12-01' , '2020-01-01' , 10 ),
( 3 , '2019-12-01' , '2020-01-31' , 1 );

select * from #Sales;

@Enigma62
Copy link
Author

Enigma62 commented Nov 3, 2020

There is also a more dynamic way to solve this

-- Dinamic
SELECT product_id,
product_name,
report_year,
(DATEDIFF(
day, -- added
CASE WHEN YEAR(period_start) < report_year THEN CONCAT(report_year, '-01-01') ELSE period_start END,
CASE WHEN YEAR(period_end) > report_year THEN CONCAT(report_year, '-12-31') ELSE period_end END
) + 1) * average_daily_sales AS total_amount
FROM (SELECT s.product_id,
product_name,
period_start,
period_end,
average_daily_sales
FROM #Sales s
INNER JOIN #Product p
ON s.product_id = p.product_id
) AS r,
(SELECT '2018' AS report_year
UNION ALL
SELECT '2019'
UNION ALL
SELECT '2020'
) AS y
WHERE YEAR(period_start) <= report_year AND
YEAR(period_end) >= report_year
ORDER BY product_id,
report_year;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant