Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the changed value in history table sql

I want to find if the value changed for a particular ID

ID PAYMENT METHOD
1 CASH
1 VISA
1 CASH
2 CASH
2 CASH
2 CASH
3 CHEQUE
3 VISA
3 VISA
4 CASH
4 CASH
4 CASH

For example, ID 1 and ID 3 changed their payment method and I want to write a query that can detect that change, thanks in advance

example for expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID PAYMENT METHOD HAS CHANGED
1 VISA
2 CHEQUE

>Solution :

You can use:

SELECT id,
       MIN(payment_method) KEEP (DENSE_RANK FIRST ORDER BY ROWNUM)
         AS payment_method
FROM   table_name
GROUP BY id
HAVING COUNT(DISTINCT payment_method) > 1

or:

SELECT *
FROM   (
  SELECT id,
         payment_method,
         ROWNUM AS ordering_column
  FROM   table_name t
)
MATCH_RECOGNIZE(
  PARTITION BY id
  ORDER     BY ordering_column
  MEASURES
    FIRST(payment_method) AS payment_method
  PATTERN (^ same+ diff)
  DEFINE
    same AS FIRST(payment_method) = payment_method,
    diff AS diff.payment_method <> same.payment_method
);

(Note: ROWNUM should be replaced by a column that will identify a deterministic ordering in the rows for each ID such as a timestamp column; however, such a column is not present in your sample data so it cannot be used. ROWNUM will just number the rows in the order that the SQL engine processes them and that processing order may be non-deterministic.)

Which both output:

ID PAYMENT_METHOD
1 CASH
3 CHEQUE

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading