sql server - SQL Select - inserting values if not exist from another table grouping by another value -
i have 2 tables
@sales --- register daily number of sales @o_date --- register opening dates
i need fill in date gaps in @sales table each available date in @o_dates , has each code available available in @sales table
please, select.
declare @sales table ( code varchar(10) not null, date1 datetime not null, value numeric(10, 2) not null ); insert @sales ( code, date1, value ) values ('q', '20140708', 51), ('q', '20140709', 3), ('q', '20140710', 5), ('q', '20140711', 6), ('q', '20140712', 2), ('q', '20140713', 7), ('q', '20140714', 24), ('q', '20140715', 24), ('x', '20140709', 25), ('x', '20140710', 16), ('x', '20140711', 66), ('x', '20140712', 23), ('x', '20140713', 35), ('x', '20140714', 57), ('c', '20140712', 97), ('c', '20140714', 71); declare @o_dates table (date2 datetime not null); insert @o_dates (date2) values ('20140608'), ('20140707'), ('20140708'), ('20140709'), ('20140710'), ('20140711'), ('20140712'), ('20140713'), ('20140714'), ('20140715'), ('20140716'), ('20140717'), ('20140718'), ('20140719'), ('20140720');
this query gives combined sales , dates each code value null missing dates in sales:
select code, date1, value @sales union ( select distinct code, date2, null value @sales, @o_dates except select code, date1, null value @sales group code, date1 ) order code, date1, value
this query inserts dates missing in sales table 0 value:
insert @sales select distinct code, date2, 0 value @sales, @o_dates except select code, date1, 0 value @sales group code, date1
i'm sure both queries can simplified using joins first solution thought of.
edit:
a join version of select query above should easy modify insert:
select distinct s.code, date2, s2.value @sales s cross join @o_dates d left join @sales s2 on s.code=s2.code , s2.date1=d.date2 order code, date2
Comments
Post a Comment