我有一个spa
表,其中包含我需要的大多数信息:
然后我加入另一个表client
,以获取last_name
字段:
我需要为每个room_code
和service_detail
获得第一个provider_start_time
,sba_date
和provider_code
,以及最后一个< / strong> provider_end_time
。
以我的图片为例,预期结果将是:
答案 0 :(得分:1)
我认为可以使用窗口函数row_number()
和last_value()
来做到这一点:
select
room_code,
service_detail,
sba_date,
provider_start_time,
provider_end_time,
last_name
from (
select
s.*,
c.last_name,
row_number() over(
partition by s.sba_date, s.provider_code
order by s.provider_start_time
) rn,
last_value(provider_end_time) over(
partition by s.sba_date, s.provider_code
order by s.provider_start_time
range between unbounded preceding and unbounded following
) provider_end_time
from spa s
inner join client c on c.client_code = s.provider_code
) t
where rn = 1
内部查询将两个表连接起来,并通过将sba_date
递增来对具有相同provider_code
和provider_start_time
的记录组中的记录进行排名;它还计算同一组中provider_end_time
的最后一个值。然后,外部查询将对每个组中的第一条记录进行过滤。
答案 1 :(得分:0)
您还可以使用某些CTE或子查询:
;WITH cte AS ( --getting min and max time for particular provider on some date
SELECT sba_date,
MIN(provider_start_time) as provider_start_time,
MAX(provider_end_time) as provider_end_time,
provider_code
FROM spa
GROUP BY sba_date, provider_code
)
-- here goes join to clients (last_name) and original table to get room and detail
SELECT s.room_code,
s.service_detail,
c.sba_date,
c.provider_start_time,
c.provider_end_time,
cl.last_name
FROM cte c
INNER JOIN client cl
ON c.provider_code = cl.client_code
INNER JOIN spa s
ON s.sba_date = c.sba_date0
AND s.provider_code = c.provider_code
AND s.provider_start_time = c.provider_start_time