The below code works fine with MSSQL. Any suggestion on how to translate this to Postgre?
;with mySource as (
SELECT 1050
LineID, 1 SeqNo, NULL Val
UNION SELECT 1050 LineID, 2
SeqNo, NULL Val
UNION SELECT 1050 LineID, 3
SeqNo, 'ABC' Val
UNION SELECT 1050 LineID, 4
SeqNo, NULL Val
UNION SELECT 1050 LineID, 5
SeqNo, NULL Val
UNION SELECT 1050 LineID, 6
SeqNo, 'CDE' Val
UNION SELECT 1050 LineID, 7
SeqNo, NULL Val
UNION SELECT 1050 LineID, 8
SeqNo, NULL Val
UNION SELECT 1050 LineID, 9
SeqNo, 'EFG' Val
UNION SELECT 1050 LineID, 10
SeqNo, NULL Val
UNION SELECT 2222 LineID, 1
SeqNo, NULL Val
UNION SELECT 2222 LineID, 2
SeqNo, 'ABC' Val
UNION SELECT 2222 LineID, 3
SeqNo, 'CDE' Val
UNION SELECT 2222 LineID, 4
SeqNo, NULL Val
UNION SELECT 2222 LineID, 5
SeqNo, NULL Val
UNION SELECT 2222 LineID, 6
SeqNo, 'EFG' Val
UNION SELECT 2222 LineID, 7
SeqNo, NULL Val
UNION SELECT 2222 LineID, 8
SeqNo, 'HIJ' Val
UNION SELECT 2222 LineID, 9
SeqNo, NULL Val
UNION SELECT 2222 LineID, 10
SeqNo, 'KLM' Val
)
Select LineID,SeqNo, Coalesce(bu,ba) Val
from mySource m
outer apply (select top 1 Val
from mySource m1
WHERE m1.LineID=m.LineID and m1.SeqNo<=m.SeqNo and Val is not null
Order by SeqNo DESC) d1(bu)
outer APPLY (SELECT TOP 1 Val
FROM mySource m3
WHERE m3.LineID=m.LineID and m3.SeqNo>= m.SeqNo AND Val IS NOT NULL
ORDER BY SeqNo) d3(ba)
ORDER BY m.LineID, m.SeqNo
The equivalent for
outer applyin Posgres would beleft join lateral. You also need to replaceTOP 1, which is T-SQL specific, withLIMIT.It is also possible to shorten the common table expression to use the
values()syntax.Looking at the query, I tend to suspect that its logic could be largely simplified with window functions (
lag()andlead()come to mind). You might want to ask another question with more details on what you are trying to accomplish, along with sample data and expected results.