我有下表:我需要捕获该日期在StartDate和EndDate之间的第一个服务日期,下面是我的语法。
表A
ServiceDate StartDate EndDate ID PROGRAM
11/25/15 12/14/15 12/17/15 1 HIGH
12/14/15 12/14/15 12/17/15 1 HIGH
1/20/16 12/14/15 12/14/15 1 HIGH
输出:
StartDate EndDate ID PROGRAM FIRST_SERVICE_DT
12/14/15 12/17/15 1 HIGH 12/14/15
SQL
SELECT *, CASE WHEN SERVICEDATE NOT BETWEEN STARTDATE AND ENDDATE THEN NULL
WHEN SERVICEDATE BETWEEN STARTDATE AND ENDDATE THEN FIRST_VALUE(TRUNC(SERVICEDATE)) OVER (PARTITION BY ID ORDER BY SERVICEDATE)
ID ORDER BY SERVICEDATE)
END FIRST_SERVICE_DT
我的查询产生了错误的结果,需要什么来获得我想要的输出?
答案 0 :(得分:1)
您可以使用min
窗口功能执行此操作。
select *
from (select t.*
,min(case when service_date between start_date and end_date then service_date end) over(partition by id) as first_service_date
from tbl t
) t
where service_date=first_service_date