每个月的最大日期

Max date for every month

在下面你可以看到我的例子 table:

test_id     test_date     test_date_from    cash_per_step
1           2020-01-01    2019-12-30        30
1           2020-01-21    2019-12-30        40
1           2020-02-28    2019-12-30        30
2           2020-01-01    2019-12-30        30
2           2020-01-21    2019-12-30        40
2           2020-02-28    2019-12-30        30

如您所见,没有唯一的 ID(遗憾的是我也无法更改它)。 我想创建一个视图,该视图仅包含每个 test_id!

每个 MONTH 包含 MAX (test_date) 的行

像这样:

test_id     test_date     test_date_from    cash_per_step
1           2020-01-21    2019-12-30        40
1           2020-02-28    2019-12-30        30
2           2020-01-21    2019-12-30        40
2           2020-02-28    2019-12-30        30

数据仅为测试数据,双倍的请见谅。我只对查询的功能感兴趣。

这应该适用于 MySQL (8.0+) 和 SQL 服务器。

SELECT DISTINCT
    test_id,
    FIRST_VALUE(test_date) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                 ORDER BY test_date desc ) as test_date,
    FIRST_VALUE(test_date_from) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                      ORDER BY test_date desc ) as test_date_from,
    FIRST_VALUE(cash_per_step) OVER (PARTITION BY test_id,MONTH(test_date), YEAR(test_date) 
                                     ORDER BY test_date desc ) as cash_per_step
FROM YourTable

这会产生相同的结果,即使它看起来像基本代码:

declare @table table (test_id int,test_date date,test_date_from date,cash_per_step float)

insert into @table

(test_id,test_date,test_date_from,cash_per_step)
values
    (1,'2020-01-01','2019-12-30',30)
,   (1,'2020-01-21','2019-12-30',40)
,   (1,'2020-02-28','2019-12-30',30)
,   (2,'2020-01-01','2019-12-30',30)
,   (2,'2020-01-21','2019-12-30',40)
,   (2,'2020-02-28','2019-12-30',30);

select
    test_id
,   max(test_date)  test_date
,   test_date_from
,   cash_per_step
from    @table
group by test_id,cash_per_step,test_date_from
order by test_id,test_date

结果:

DEMO

;WITH CTE AS
(
  SELECT *, 
         ROW_NUMBER () OVER (PARTITION BY SUBSTRING(CONVERT(VARCHAR(20),test_date),1,7), 
         test_id ORDER BY TEST_ID,TEST_DATE DESC) RN 
  FROM @table
)
SELECT * FROM CTE WHERE RN =1 ORDER BY TEST_ID