每个月的最大日期

kmpatx3s  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(346)

下面是我的表格示例:

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\u id每个月的最大值(test\u 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

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

31moq8wy

31moq8wy1#

这应该可以在mysql(8.0+)和sql server中使用。

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
v7pvogib

v7pvogib2#

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

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

结果:

请参见演示

csga3l58

csga3l583#

;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

相关问题