Firstly, let me introduce you to table aliases - see how much easier your query is to read.
Now you can solve your problem using the row_number()
function and then only selecting row numbers 1.
with cte as (
select K.id Col1, Z.adresKoncowy Col2, ZK.id Col3
, row_number() over (partition by K.id order by ZK.id desc) RowNum
from FirmaTransportowa.dbo.Kurier K
join FirmaTransportowa.dbo.ZlecenieKurier ZK on K.id = ZK.kurierId
join FirmaTransportowa.dbo.Zlecenie Z on Z.id = ZK.zlecenieId
where K.id = ZK.kurierId
-- order by ZK.id desc
)
select Col1, Col2, Col3
from cte
where RowNum = 1
order by Col1 desc;
Note: Do use better column aliases than I have - I don't know what your columns represent but you do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…