-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1251_Average_Selling_Price.sql
57 lines (46 loc) · 2.6 KB
/
1251_Average_Selling_Price.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
-- Source: https://leetcode.com/problems/average-selling-price/description/?envType=study-plan-v2&envId=top-sql-50
-- Table: Prices
-- +---------------+---------+
-- | Column Name | Type |
-- +---------------+---------+
-- | product_id | int |
-- | start_date | date |
-- | end_date | date |
-- | price | int |
-- +---------------+---------+
-- (product_id, start_date, end_date) is the primary key for this table.
-- Each row of this table indicates the price of the product_id in the period from start_date to end_date.
-- For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.
-- Table: UnitsSold
-- +---------------+---------+
-- | Column Name | Type |
-- +---------------+---------+
-- | product_id | int |
-- | purchase_date | date |
-- | units | int |
-- +---------------+---------+
-- There is no primary key for this table, it may contain duplicates.
-- Each row of this table indicates the date, units, and product_id of each product sold.
-- Write an SQL query to find the average selling price for each product. average_price should be rounded to 2 decimal places.
-- Return the result table in any order.
------------------------------------------------------------------------------
-- SQL Schema
Create table If Not Exists Prices (product_id int, start_date date, end_date date, price int)
Create table If Not Exists UnitsSold (product_id int, purchase_date date, units int)
Truncate table Prices
insert into Prices (product_id, start_date, end_date, price) values ('1', '2019-02-17', '2019-02-28', '5')
insert into Prices (product_id, start_date, end_date, price) values ('1', '2019-03-01', '2019-03-22', '20')
insert into Prices (product_id, start_date, end_date, price) values ('2', '2019-02-01', '2019-02-20', '15')
insert into Prices (product_id, start_date, end_date, price) values ('2', '2019-02-21', '2019-03-31', '30')
Truncate table UnitsSold
insert into UnitsSold (product_id, purchase_date, units) values ('1', '2019-02-25', '100')
insert into UnitsSold (product_id, purchase_date, units) values ('1', '2019-03-01', '15')
insert into UnitsSold (product_id, purchase_date, units) values ('2', '2019-02-10', '200')
insert into UnitsSold (product_id, purchase_date, units) values ('2', '2019-03-22', '30')
-- MS SQL Server Code
SELECT p.product_id, ROUND(CAST(SUM(p.price * u.units) AS FLOAT)/SUM(u.units),2) AS 'average_price'
FROM Prices p
JOIN UnitsSold u
ON p.product_id = u.product_id
AND u.purchase_date BETWEEN p.start_date AND p.end_date
GROUP BY p.product_id