1

The following query doesn't work, because Firebird (2.1) won't recognize the subquery's column. How can I rewrite it to work?

SELECT I.InvoiceID,
  I.PayByDate,
  (SELECT FIRST 1 I2.PayByDate
  FROM Invoices I2
  WHERE I2.OriginalInvoiceID = I.InvoiceID
    AND I2.IsDraft < 1
  ORDER BY I2.InvoiceID DESC) AS NewPayByDate
FROM Invoices I
WHERE
  I.IsDraft < 1
ORDER BY
  IIF(NewPayByDate IS NULL,
    PayByDate,
    NewPayByDate),
  I.InvoiceRefNum
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Steve
  • 2,510
  • 4
  • 34
  • 53

1 Answers1

1

Use a subquery:

SELECT InvoiceID, PayByDate, NewPayByDate
FROM (SELECT I.*
             (SELECT FIRST 1 I2.PayByDate
              FROM Invoices I2
              WHERE I2.OriginalInvoiceID = I.InvoiceID AND
                    I2.IsDraft < 1
              ORDER BY I2.InvoiceID DESC
             ) AS NewPayByDate
      FROM Invoices I
      WHERE I.IsDraft < 1
     ) I
ORDER BY IIF(NewPayByDate IS NULL, PayByDate, NewPayByDate),
         I.InvoiceRefNum;

I would also recommend using COALESCE() in the ORDER BY:

ORDER BY COALESCE(NewPayByDate, PayByDate),
         I.InvoiceRefNum;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I.InvoiceRefNum is missing from the second SELECT, but apart from it, it works like charm, thanks! – Steve Mar 08 '21 at 17:15