Skip to content

Commit 7af2b43

Browse files
committed
solve problem 39
1 parent 17c1e38 commit 7af2b43

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

MySol/Average selling price.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
把資料庫建起來的SQL
2+
現在建table會在名稱後綴題目編號,這樣避免table名稱撞名
3+
```SQL
4+
create table Prices_39 (
5+
product_id int,
6+
start_date date,
7+
end_date date,
8+
price int,
9+
PRIMARY KEY (product_id, start_date, end_date)
10+
);
11+
12+
INSERT INTO Prices_39 (product_id, start_date, end_date, price) VALUES
13+
(1, "2019-02-17", "2019-02-28", 5),
14+
(1, "2019-03-01", "2019-03-22", 20),
15+
(2, "2019-02-01", "2019-02-20", 15),
16+
(2, "2019-02-21", "2019-03-31", 30);
17+
18+
19+
create table UnitsSold_39 (
20+
product_id int,
21+
purchase_date date,
22+
units int
23+
);
24+
25+
INSERT INTO UnitsSold_39 (product_id, purchase_date, units) VALUES
26+
(1, "2019-02-25", 100),
27+
(1, "2019-03-01", 15),
28+
(2, "2019-02-10", 200),
29+
(2, "2019-03-22", 30);
30+
```
31+
32+
查詢的SQL
33+
```SQL
34+
SELECT product_id, round(SUM(temp.units * temp.price) / SUM(temp.units), 2) average_price FROM
35+
(SELECT unitssold_39.product_id, price, units FROM unitssold_39
36+
LEFT JOIN prices_39 ON unitssold_39.product_id = prices_39.product_id
37+
AND unitssold_39.purchase_date between prices_39.start_date AND prices_39.end_date) AS temp
38+
group by product_id;
39+
```
40+
41+
先join`UnitsSold` table和`Prices` table,用left join可以確保`UnitSold`都會在,這題先把所有購買紀錄都對上對應時間區間的間隔,暫存為table temp(subquery's result),在對temp table做query。
42+
如果是`natural join`就不用在合併條件那邊加上product_id要相同,而且會使用一般的where clause來過濾日期不相符的rows。如下
43+
```SQL
44+
SELECT product_id, round(SUM(temp.units * temp.price) / SUM(temp.units), 2) average_price FROM
45+
(SELECT unitssold_39.product_id, price, units FROM unitssold_39
46+
natural join prices_39 where unitssold_39.purchase_date between prices_39.start_date AND prices_39.end_date) AS temp
47+
group by product_id;
48+
```

0 commit comments

Comments
 (0)