There is a table that stores account data for everyday. I want to find out the difference in data between today and yesterday. The query for table creation and insert statements are below :
CREATE TABLE daily_account_data (id varchar(6), Name varchar (20), DS_DW_Id varchar(4), flag_1 varchar(5), flag_2 varchar(5), Insert_date date );
INSERT INTO daily_account_data VALUES('A01R11', 'Gene Graham', 'PT12', 'TRUE', 'FALSE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald', 'PT15', 'TRUE', 'TRUE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R19', 'John Doe', 'PT24', 'FALSE','TRUE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe', 'PT26', 'TRUE', 'FALSE', '2023-06-01');
INSERT INTO daily_account_data VALUES('A01R11', 'Gene Wilder', 'PT12', 'TRUE', 'FALSE', '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R16', 'Molly Ringwald', 'PT15', 'TRUE', 'TRUE', '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R19', 'John Doe', 'PT24', 'TRUE', 'TRUE', '2023-06-02');
INSERT INTO daily_account_data VALUES('A01R34', 'Jane Doe', 'PT26', 'TRUE', 'FALSE', '2023-06-02');
I have the query to find the difference in the data of the 2 days.
SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-02'
EXCEPT
SELECT id, name, DS_DW_Id, flag_1, flag_2 FROM daily_account_data WHERE Insert_date = '2023-06-01';
But I can't figure out to get the data in the pseudo column. The last column is changed data. On 1st June data the name of the id A01R11 is Gene Graham and on 2nd it is Gene Wilder. The pseudo column should display "Name change".
Similarly for id A01R19 (John Doe) the value for flag_1 has changed to TRUE. The pseudo column should display "flag_1 change".
The output should look like :
id | Name | DS_DW_Id | flag_1 | flag_2 | Data Change |
---|---|---|---|---|---|
A01R11 | Gene Wilder | PT12 | TRUE | FALSE | Name Change |
A01R19 | John Doe | PT24 | TRUE | TRUE | flag_1 Change |
You can join the table and subtract the date. If the order of the record is correct (the previous day must be the previous record, you can use the window function(LEAD ))
select
a.id
,a.Name
,a.DS_DW_Id
,a.flag_1
,a.flag_2
,iif(a.Name=b.Name ,'',' Name Change')
+iif(a.DS_DW_Id=b.DS_DW_Id ,'',' DS_DW_Id Change')
+iif(a.flag_1=b.flag_1 ,'',' flag_1 Change')
+iif(a.flag_2=b.flag_2 ,'',' flag_2 Change') AS [Data Change]
from daily_account_data a
inner join(
select *
from daily_account_data b
)b on a.id=b.id
and DATEADD(day,-1, b.Insert_date)=a.Insert_date
where a.Name<>b.Name
or a.DS_DW_Id<>b.DS_DW_Id
or a.flag_1<>b.flag_1
or a.flag_2<>b.flag_2