当月产品最低价

cheapest price for product in month

我有一个product_pricestable

ID      Product_id     Price   Price_date
1            1           5      2021-10-01
2            1           6      2021-10-25
3            2           5      2021-10-01
4            2           6      2021-10-25
5            1           3      2021-09-01
6            1           5      2021-09-25
7            2           7      2021-09-01
8            2           3      2021-09-25

我如何通过SQL查询

记录每个月最便宜的产品价格
ID      Product_id     Price   Price_date
1            1           5      2021-10-01
3            2           5      2021-10-01
5            1           3      2021-09-01
8            2           3      2021-09-25

您没有标记您正在使用的 RDBMS,但如果它是 SQL 服务器,这里有一个示例解决方案:

declare @product_prices table (
    ID int,
    Product_id int,
    Price int,
    Price_date date
)

insert into @product_prices values
(1,1,5,'2021-10-01'),
(2,1,6,'2021-10-25'),
(3,2,5,'2021-10-01'),
(4,2,6,'2021-10-25'),
(5,1,3,'2021-09-01'),
(6,1,5,'2021-09-25'),
(7,2,7,'2021-09-01'),
(8,2,3,'2021-09-25')

select
    datepart(year,Price_date) as [Year],
    datepart(month,Price_date) as [Month],
    datename(month,Price_date) as [MonthName],
    Product_id,
    min(Price) as LowestPrice
from @product_prices
group by
    datepart(year,Price_date),
    datepart(month,Price_date),
    datename(month,Price_date),
    Product_id
order by 1, 2

结果:

/-----------------------------------------------------\
| Year | Month | MonthName | Product_id | LowestPrice |
|------|-------|-----------|------------|-------------|
| 2021 |   9   | September |      1     |      3      |
| 2021 |   9   | September |      2     |      3      |
| 2021 |  10   | October   |      1     |      5      |
| 2021 |  10   | October   |      2     |      5      |
\-----------------------------------------------------/