SAP HANA-不同行中列值之间的差异

时间:2018-09-17 08:46:25

标签: sql window-functions hana

我有一个具有以下结构的表

ID - Task  | Performed BY | Start Date | End Date  
1 --- Task 3 --- John --------- 9/16/2017 - 9/17/2017  
1 --- Task 2 --- Jim  ----------- 9/14/2017 - 9/16/2017  
1 --- Task 1 --- John  --------- 9/10/2107 - 9/13/2017  
2 --- Task 2 --- Jane --------- 9/14/2017 - 9/15/2017  
2 --- Task 1 --- Claire -------- 9/12/2017 - 9/13/2017  

我需要创建一个新列,以显示执行SAP HANA中每个ID的所有任务所需的总时间(持续时间)。即每个ID的最后一个任务的结束日期减去第一个任务的开始日期。

以下是我需要的结果:

ID - Task  | Performed BY | Start Date | End Date | Duration  
1 --- Task 3 --- John --------- 9/16/2017 - 9/17/2017 -- 7 Days  
1 --- Task 2 --- Jim  ----------- 9/14/2017 - 9/16/2017 -- 7 Days  
1 --- Task 1 --- John  --------- 9/10/2107 - 9/13/2017 -- 7 Days  
2 --- Task 2 --- Jane --------- 9/14/2017 - 9/15/2017 -- 3 Days  
2 --- Task 1 --- Claire -------- 9/12/2017 - 9/13/2017 -- 3 Days 

这可以使用以下查询在SQL中完成:

选择     ID,任务,执行者,开始日期,结束日期,
        DATEDIFF(day,
                 MIN(开始日期)超过(按ID分配),
                 MAX(结束日期)OVER(按ID划分的部分))持续时间
从表;

我需要使用SAP HANA来执行此任务。非常感谢您提供有关如何将此SQL查询迁移到HANA的任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

SAP HANA支持标准SQL window functions,还提供日期计算功能days_between
您可以这样编写代码:

SELECT "ID", "Task", "Performed By", "Start Date", "End Date"
     , DAYS_BETWEEN(MIN("Start Date") OVER (PARTITION BY "ID"),
                   MAX("End Date") OVER (PARTITION BY "ID")) "Duration"
FROM tasks
order by "ID", "Task";

ID  Task    Performed By    Start Date  End Date    Duration
1   Task 1  John            10/09/2017  13/09/2017  7       
1   Task 2  Jim             14/09/2017  16/09/2017  7       
1   Task 3  John            16/09/2017  17/09/2017  7       
2   Task 1  Claire          12/09/2017  13/09/2017  3       
2   Task 2  Jane            14/09/2017  15/09/2017  3