postgresql 用于选择的SQL任务

vkc1a9a2  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(133)

练习:计算2022年所有汽车按月细分的平均价格,考虑到折扣,将结果按月升序排序,平均价格四舍五入到小数点后两位。
来源:brandorigin
| ID|汽车|价格|日期|
| --|--|--|--|
| 1 |拉达·维斯塔,灰色|11243.44| 2019-12-15 2019-12-15 2019-12-15|
| 2 |宝马F80,红色|63761.75| 2019年1月29日|
| 3 |现代伊兰特|42584.06| 2021-08-29 2021-08-29 2021-08-29|
| 4 |拉达萨马拉,粉红色|9902.40| 2017-02-08 2017-02-08|
| 5 |奥迪S3,灰色|18307.80| 2020-05-12 2020-05-12 2020-05-12|
| 1000 |......这是什么?|......这是什么?|......这是什么?|
我的SQL查询:

SELECT EXTRACT(MONTH FROM date) AS month, EXTRACT(YEAR FROM date)  AS year, ROUND(AVG(price * (100 - discount) / 100), 2) AS price_avg
FROM brandorigin
WHERE EXTRACT(YEAR FROM date) = '2022'
GROUP BY date 
ORDER BY date ASC

字符串
table:brandorigin(with my sql-query)
| ID|月|年|价格平均|
| --|--|--|--|
| 1 | 1 | 2022 |38395.35|
| 2 | 1 | 2022 |21578.42|
| 3 | 1 | 2022 |44720.55|
| 4 | 2 | 2022 |68387.55|
| 5 | 3 | 2022 |29668.59|
| 91 |......这是什么?|......这是什么?|......这是什么?|
我的汇总表中的月份是重复的,所以我需要以某种方式得到第一个月所有汽车的总和,然后是第二个月所有汽车的总和,依此类推。如果没有重复,应该正好有12行(月)。如何实现这一点?
summary table

nwsw7zdq

nwsw7zdq1#

GROUP BY和ORDER BY都不正确。两者都采用完整的日期,而不仅仅是月份和年份。

SELECT EXTRACT(MONTH FROM date) AS month, EXTRACT(YEAR FROM date)  AS year, ROUND(AVG(price * (100 - discount) / 100), 2) AS price_avg
FROM brandorigin
WHERE EXTRACT(YEAR FROM date) = '2022'
GROUP BY EXTRACT(MONTH FROM date),  EXTRACT(YEAR FROM date)
ORDER BY EXTRACT(MONTH FROM date),  EXTRACT(YEAR FROM date);

字符串
您也可以使用列编号1和2:

SELECT EXTRACT(MONTH FROM date) AS month, EXTRACT(YEAR FROM date)  AS year, ROUND(AVG(price * (100 - discount) / 100), 2) AS price_avg
FROM brandorigin
WHERE EXTRACT(YEAR FROM date) = '2022'
GROUP BY 1,2
ORDER BY 1,2;

相关问题