Select distinct

a.[register] as [Terminal]

,format(a.[open_date],'yyyy-MM-dd') as [Date]

,a.[open_birno] as [Beg Invoice]

,a.[clos_birno] as [Ending Invoice]

,isnull(d.rd_tamount,0)

,isnull(c.rd_tamount,0)

,isnull(e.rd_tamount,0)

,isnull(f.rd_tamount,0)

,isnull(g.rd_tamount,0)

,isnull(h.rd_tamount,0)

,isnull(i.rd_tamount,0)

,isnull(j.rd_tamount,0)

,isnull(k.rd_tamount,0)

,isnull(l.rd_tamount,0)

,isnull(m.rd_tamount,0)

,isnull(n.rd_tamount,0)

,isnull(o.rd_tamount,0)

,isnull(p.rd_tamount,0)

,isnull(q.rd_tamount,0)

,isnull(b.rd_tamount,0)

FROM [dbo].[REGHIST] a

left join dbo.regdtail b on a.open_date = dbo.grouptodate(b.rd_group)

and (b.rd_type='M' and b.rd_code='VE')

left join dbo.regdtail c on a.open_date = dbo.grouptodate(c.rd_group)

and (c.rd_type='T' and c.rd_code ='15')

left join dbo.regdtail d on a.open_date = dbo.grouptodate(d.rd_group)

and (d.rd_type='T' and d.rd_code ='0')

left join dbo.regdtail e on a.open_date = dbo.grouptodate(e.rd_group)

and (e.rd_type='T' and e.rd_code ='23')

left join dbo.regdtail f on a.open_date = dbo.grouptodate(f.rd_group)

and (f.rd_type='T' and f.rd_code ='28')

left join dbo.regdtail g on a.open_date = dbo.grouptodate(g.rd_group)

and (g.rd_type='T' and g.rd_code ='43')

left join dbo.regdtail h on a.open_date = dbo.grouptodate(h.rd_group)

and (h.rd_type='T' and h.rd_code ='35')

left join dbo.regdtail i on a.open_date = dbo.grouptodate(i.rd_group)

and (i.rd_type='T' and i.rd_code ='17')

left join dbo.regdtail j on a.open_date = dbo.grouptodate(j.rd_group)

and (j.rd_type='T' and j.rd_code ='42')

left join dbo.regdtail k on a.open_date = dbo.grouptodate(k.rd_group)

and (k.rd_type='D' and k.rd_code ='A1')

left join dbo.regdtail l on a.open_date = dbo.grouptodate(l.rd_group)

and (l.rd_type='D' and l.rd_code ='05')

left join dbo.regdtail m on a.open_date = dbo.grouptodate(m.rd_group)

and (m.rd_type='D' and m.rd_code ='A2')

left join dbo.regdtail n on a.open_date = dbo.grouptodate(n.rd_group)

and (n.rd_type='D' and n.rd_code ='02')

left join dbo.regdtail o on a.open_date = dbo.grouptodate(o.rd_group)

and (o.rd_type='D' and o.rd_code ='10')

left join dbo.regdtail p on a.open_date = dbo.grouptodate(p.rd_group)

and (p.rd_type='D' and p.rd_code ='11')

left join dbo.regdtail q on a.open_date = dbo.grouptodate(q.rd_group)

and (q.rd_type='T' and q.rd_code ='26')

where a.register = 'A5'

and a.open_date between '2015-06-04' and '2015-06-04'

group by a.[register], a.[open_date], a.[open_birno], a.[clos_birno]

, b.rd_tamount, c.rd_tamount, d.rd_tamount

, e.rd_tamount, f.rd_tamount, g.rd_tamount

, h.rd_tamount, i.rd_tamount, j.rd_tamount

, k.rd_tamount, l.rd_tamount, m.rd_tamount

, n.rd_tamount, o.rd_tamount, p.rd_tamount

, q.rd_tamount