标题和明细表查询

时间:2019-07-19 22:06:44

标签: sql

我有一个主表,其中有遇到ID和文本,还有详细表,匹配字段是遇到ID和文本。从详细信息表中,我需要获取按日期和时间显示的最新记录。

我不知道该怎么做。我认为前1名应该起作用。

select top 1 om.txt_order_enc_id, txt_act_text_display, txt_actionDate, txt_action from order_management_data_ om
inner join order_ o on om.txt_order_enc_id = o.encounterID
                    and om.txt_act_text_display = o.actTextDisplay
where o.actstatus = 'ordered'
and o.actclass = 'REFR'
and o.encounterdate < '20180610'
order by o.encounterdate desc

预期结果。 最新记录遇到的ID,文本,明细表中的状态。

1 个答案:

答案 0 :(得分:0)

首先基于group by创建一个encounterID。为其创建row index。并筛选出每个组的前1条记录。

    ; with cte as (
    select row_number () (partition by o.encounterID order by o.encounterdate desc) as Slno,
    om.txt_order_enc_id, txt_act_text_display, txt_actionDate, txt_action from order_management_data_ om
    inner join order_ o on om.txt_order_enc_id = o.encounterID
                        and om.txt_act_text_display = o.actTextDisplay
    where o.actstatus = 'ordered'
    and o.actclass = 'REFR'
    and o.encounterdate < '20180610'
    )
    select * from cte where Slno = 1