SELECT a.TruckOrder,a.AddrType ,a.OpeaterBy ,c.DeptName,
b.Driver+‘-‘+CONVERT(VARCHAR(16),e.OpeaterDT,121)AS DOpeaterDT,
b.Driver+‘-‘+CONVERT(VARCHAR(16),f.OpeaterDT,121)AS COpeaterDT,
b.Driver+‘-‘+CONVERT(VARCHAR(16),g.OpeaterDT,121)AS LOpeaterDT,
b.Driver+‘-‘+CONVERT(VARCHAR(16),h.OpeaterDT,121)AS HOpeaterDT,
b.Driver,b.TransType,CONVERT(VARCHAR(16),b.TruckDT,121)AS TruckDT,b.TruckNo,b.TruckModel
INTO #TruckWay
FROM dbo.T_TruckWay AS a
JOIN dbo.T_TruckOrder AS b ON a.TruckOrder=b.TruckOrder AND b.CFMFlag=‘Y‘ AND b.AuctionStatus=‘Y‘
JOIN BAS_DepartMent AS c ON b.DeptCode=c.DeptCode
JOIN (SELECT TruckOrder,MAX(OpeaterDT)AS OpeaterDT FROM T_TruckWay GROUP BY TruckOrder) AS d ON a.TruckOrder=d.TruckOrder AND a.OpeaterDT=d.OpeaterDT
LEFT JOIN T_TruckWay AS e ON a.TruckOrder=e.TruckOrder AND e.AddrType=3
LEFT JOIN T_TruckWay AS f ON a.TruckOrder=f.TruckOrder AND f.AddrType=4
LEFT JOIN T_TruckWay AS g ON a.TruckOrder=g.TruckOrder AND g.AddrType=5
LEFT JOIN T_TruckWay AS h ON a.TruckOrder=h.TruckOrder AND h.AddrType=6
SELECT * FROM #TruckWay
SELECT COUNT(1) AS total FROM #TruckWay