create table [New1]
([Posting Date] date references [sample].[dbo].[Posting Date_PRL]([Posting Date]),
[Order No] nvarchar(20) collate Latin1_General_100_CS_AS references [sample].[dbo].[Order No_PRL]([Order No]),
[Prod_Order No] nvarchar(20) collate Latin1_General_100_CS_AS references [sample].[dbo].[Prod_ OrderNo_PRL]([Prod_Order No]),
[No] nvarchar(20) collate Latin1_General_100_CS_AS references [sample].[dbo].[No_PRL] ([No]),
[Item Category Code] nvarchar(10) collate Latin1_General_100_CS_AS references [sample].[dbo].[Item Category Code_PRL] ([Item Category Code]),
[Location Code] nvarchar(10) collate Latin1_General_100_CS_AS references [sample].[dbo].[Location Code_PRL]([Location Code]),
[Spcl Order_Purch] tinyint references [sample].[dbo].[Spcl Order_PRL] ([Spcl Order_Purch]),
[Spcl_PO] tinyint references [sample].[dbo].[Spcl Order_PO] ([Spcl Order]),
Quantity decimal(15,2))--[Vendor Id] int references [dbo].[Dim Vendor] ([Vendor Id] )
insert into [New1]([Posting Date],[Order No],[Prod_Order No],[No],[Item Category Code],[Location Code],[Spcl Order_Purch],[Spcl_PO],[Quantity])
select CONVERT(date, a.[Posting Date], 102),sum(a.mes) as Quantity,min(a.Spcl_PO) as Spcl_PO ,
min(a.OrderNo) as OrderNo,min(a.[Prod_Order No]) as Prod_OrderNo,min(a.[No]) as [No],min(a.[Item Category Code]) as [Item Category Code],
min(a.[Location Code]) as [Location Code],min(a.[Spcl Order_Purch]) as [Spcl Order_Purch] from (
select A.[Finished Date] as [Posting Date],min(h.[Spcl Order]) as Spcl_PO,'' as OrderNo,'' as [Prod_Order No],'' as [No],'' as [Item Category Code],'' as [Location Code],'' as [Spcl Order_Purch],
(case when sum(A.[Quantity]) is null then 0 else sum(A.[Quantity]) END) as mes
from [Table1] A
inner join [sample].[dbo].[Spcl Order_PO] as h on A.[Spcl Order]=h.[Spcl Order]
where ((A.[Status]=4) ) group by A.[Finished Date] union all
select A.[Posting Date] as [Posting Date],'' as Spcl_PO,min(c.[Order No]),min(d.[Prod_Order No]),min(e.[No]),min(f.[Item Category Code]),min(g.[Location Code]),
min(i.[Spcl Order_Purch]),(case when sum(A.[Quantity]) is null then 0 else sum(A.[Quantity]) END) as mes
from [Table2] A
inner join [sample].[dbo].[Posting Date_PRL] as b on a.[Posting Date]=b.[Posting Date]
inner join [sample].[dbo].[Order No_PRL] as c on a.[Order No_]=c.[Order No]
inner join [sample].[dbo].[Prod_ OrderNo_PRL] as d on a.[Prod_ Order No_]=d.[Prod_Order No]
inner join [sample].[dbo].[No_PRL] as e on a.[No_]=e.[No]
inner join [sample].[dbo].[Item Category Code_PRL] as f on a.[Item Category Code]=f.[Item Category Code]
inner join [sample].[dbo].[Location Code_PRL] as g on a.[Location Code]=g.[Location Code]
inner join [sample].[dbo].[Spcl Order_PRL] as i on a.[Spcl Order]=i.[Spcl Order_Purch]
where ((A.[Item Category Code] = 'STYLES') and (A.[Prod_ Order No_]='') AND (A.[Quantity]>0) )
group by A.[Posting Date],a.[No_]) as a group by a.[Posting Date]