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

Generate dummy values if the Column data (X,Y,Z) is absent for a date

I have a table A as :
enter image description here

and I need to generate output like below:

enter image description here

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

So, whenever x,y,z column values for "CODE" is missing for a particular date, we need to generate dummy rows with 0 values as showing in the output.

>Solution :

declare @temp table(id int IDENTITY(1,1), rowDate date, code varchar(1), val int);
insert into @temp(rowdate, code, val)values('01.08.2023', 'x', 100);
insert into @temp(rowdate, code, val)values('01.08.2023', 'y', 100);
insert into @temp(rowdate, code, val)values('01.08.2023', 'z', 100);
insert into @temp(rowdate, code, val)values('01.08.2023', 'a', 100);
insert into @temp(rowdate, code, val)values('01.08.2023', 'b', 100);
insert into @temp(rowdate, code, val)values('01.08.2023', 'c', 100);
insert into @temp(rowdate, code, val)values('02.08.2023', 'x', 100);
insert into @temp(rowdate, code, val)values('02.08.2023', 'y', 100);
insert into @temp(rowdate, code, val)values('02.08.2023', 'z', 100);


select 
tempTable.rowDate, 
tempTable.code, 
COALESCE(origTable.val, tempTable.val) as val 
from
    (select 
    a.rowDate, 
    b.code, 
    0 as val
    from (select distinct rowdate from @temp) as a 
    inner join (select distinct code from @temp) as b 
    on 1=1) 
    as tempTable
left join @temp as origTable
on tempTable.rowDate = origTable.rowDate 
and tempTable.code = origTable.code
order by tempTable.rowDate, tempTable.code
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