-1

在下面,您可以看到我的表格的示例:

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

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

4

3 回答 3

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
于 2020-07-10T08:37:46.977 回答
0

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

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

结果:

预期成绩

演示

于 2020-07-10T09:12:05.227 回答
-1
;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
于 2020-07-11T12:40:49.197 回答