包括子查询中的连接

时间:2018-04-19 13:00:28

标签: sql sql-server

我尝试进行查询以获取记录重复的最后日期时间。

select * from OCCONTROLMERCADERIA om 
join OCCONTROLMERCADERIALINEAS oml on om.occontrolid=oml.occontrolid
where om.OCControlNroId=5519337

这回复:

Result Query 1

我想要的查询应该返回寄存器在蓝框中。

我找到了这个查询(没有连接):

with
    p as (select * from OCCONTROLMERCADERIA om where om.OCControlNroId=5519337),
    p_rnk as (
        select *, row_number() over (partition by OCControlNroId order by OCControlFecha desc) as rn
        from p
    )
select * from p_rnk where rn = 1 order by OCControlNroId;

这回复:

Result Query 2

没关系,如果在第一张图片中看到蓝色框,则最后一个日期对应于记录ID 13756.

但是我需要查询返回对应于id 13756的3条记录,而不仅仅是一条记录,所以我尝试应用连接。

with
    p as (select * from OCCONTROLMERCADERIA om 
    join OCCONTROLMERCADERIALINEAS oml on om.occontrolid=oml.occontrolid
    where om.OCControlNroId=5519337),
    p_rnk as (
        select *, row_number() over (partition by OCControlNroId order by OCControlFecha desc) as rn
        from p  
    )
select * from p_rnk where rn = 1 order by OCControlNroId;

但这回归:

'p'多次指定了'OCControlId'列。

我正在尝试这个(选择om。*):

with
    p as (select om.* from OCCONTROLMERCADERIA om 
    join OCCONTROLMERCADERIALINEAS oml on om.occontrolid=oml.occontrolid
    where om.OCControlNroId=5519337),
    p_rnk as (
        select *, row_number() over (partition by OCControlNroId order by OCControlFecha desc) as rn
        from p  
    )
select * from p_rnk where rn = 1 order by OCControlNroId;

错误消失但只返回一条记录,而不是三条记录。这可能是问题吗?

感谢您的帮助!

0 个答案:

没有答案