【问题标题】:Max date for every month每个月的最大日期
【发布时间】:2020-10-30 22:54:29
【问题描述】:

在下面你可以看到我的表格的一个例子:

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 还是 SQL Server?它们是完全不同的产品......

标签: mysql sql sql-server tsql denodo


【解决方案1】:

这应该适用于 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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      【解决方案3】:
      ;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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        • 1970-01-01
        相关资源
        最近更新 更多