0

我有样本数据

 ID  Name  Amount  cal_amt Run_amt  Dates
 1   Test   15000    0.00  15000    2020-06-01
 1   Test   15000    0.00  30000    2020-04-01
 1   Test   15000    12000 30000    2020-05-01
 2   Test_1   18000   0.00  25000    2020-06-01
 2   Test_1   18000   0.00  35000    2020-04-01
 2   Test_1   18000   16000 35000    2020-05-01

我需要获得 MAX(月)的 Run_Amount 即:2020-06-01 --> 15000

需要获取当月的 cal_amt 即:2020-05-01 --> 12000 和 0.00 也与本月相关 2020-04-01

我需要得到这样的输出:

 ID  Name  Amount  cal_amt Run_amt  
 1   Test   15000    12000  15000 
 2   Test_1 18000    16000  25000

它是示例数据,但还有另外几列我已经尝试使用MAX() 条件

ROW_NUMBER()over (PARTITION BY run_amt order by Date )

谁能建议我最好的方法

4

1 回答 1

0

使用ROW_NUMBER()窗口函数获取具有Run_amt最大月份的行,然后使用条件聚合:

SELECT t.ID, t.Name, t.Amount,
  MAX(CASE WHEN LAST_DAY(Date) = LAST_DAY(CURRENT_DATE) THEN cal_amt END) cal_amt,
  MAX(CASE WHEN t.rn = 1 THEN Run_amt END) Run_amt
FROM (
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) rn
  FROM tablename
) t
GROUP BY t.ID, t.Name, t.Amount

或者:

SELECT t.ID, t.Name, t.Amount,
       MAX(t.cal_amt) cal_amt,
       MAX(t.Run_amt) Run_amt
FROM (
  SELECT ID, Name, Amount,
    MAX(CASE WHEN LAST_DAY(Date) = LAST_DAY(CURRENT_DATE) THEN cal_amt END) 
      OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) cal_amt,
    FIRST_VALUE(Run_amt) OVER (PARTITION BY ID, Name, Amount ORDER BY Date DESC) Run_amt
  FROM tablename
) t  
GROUP BY t.ID, t.Name, t.Amount

请参阅演示
结果:

> ID | Name   | Amount | cal_amt | Run_amt
> -: | :----- | -----: | ------: | ------:
>  1 | Test   |  15000 |   12000 |   15000
>  2 | Test_1 |  18000 |   16000 |   25000
于 2020-05-01T11:52:31.030 回答