You can combine your three tables together to make one data set. You can then use PIVOT to transfer the SUM to columns.
That should work. Although I have not tested it with any data.
SELECT [Tleave_sick_leave], [Tleave_other_leave], [Tleave_vleave] FROM ( SELECT 'Tleave_sick_leave' [Table], [staff_key], [days_applied], [from_date], [to_date] FROM [Tleave_sick_leave] UNION ALL SELECT 'Tleave_other_leave' [Table], [staff_key], [days_applied], [from_date], [to_date] FROM [Tleave_other_leave] UNION ALL SELECT 'Tleave_vleave' [Table], [staff_key], [days_applied], [from_date], [to_date] FROM [Tleave_vleave] ) [PivotData] PIVOT ( SUM([days_applied]) FOR [Table] IN ( [Tleave_sick_leave], [Tleave_other_leave], [Tleave_vleave] ) ) [Data] WHERE [staff_key] = 131 AND [from_date] >= '2011/4/1 00:00:00' AND [to_date] <= '2011/4/30 00:00:00'
NOTE. This is an approach based on SQL Server 2005. If you have 2000 or lower, you will need to find Leavenβs answer that will actually do the same.
source share