假设 Sql Server 2005+
Declare @CalenderMonths Table ([Month] Varchar(20),FiscalOrder Int)
Insert Into @CalenderMonths Values
('June',1),('July',2),('August',3),('September',4),('October',5),('November',6),
('December',7),('January',8),('February',9),('March',10),('April',11),('May', 12)
Declare @Employee Table(employee varchar(50), [month] Varchar(20), amount int )
Insert Into @Employee Values('john', 'July', 10),('john', 'July',3),('john','August',2),('mary','June',2),('mary', 'February',5)
;with cte as
(
Select employee,[month],TotalAmount = sum(amount)
from @Employee
group by employee,[month]
)
select x.[Month],x.employee,amount = coalesce(c.TotalAmount,0)
from (
select distinct c.[Month],e.employee
from @CalenderMonths c cross join cte e)x
left join cte c on x.[Month] = c.[Month] and x.employee = c.employee
order by 2