2012-10-17 63 views
1

使用SQL Server 2005的加入並彙總在兩列 - 每個月甚至幾個月沒有數據?

我有個日曆月

Month, fiscalorder 
june,1 
july,2 
.. 
may,12 

一個表,並與員工另一個表和重複每月數額

employee, month, amount 
john, july, 10 
john, july, 3 
john, august,2 
mary, june, 2 
mary, feb, 5 

我需要參加並通過聚合這些月,但每個月(甚至沒有數據的月份)報告每個僱員,但僱員然後財政秩序。

輸出:

june, john, 0 
july, john, 13 
august,john,2 
sept, john, 0 
.. 
june,mary,2 

回答

1

假設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 
1
SELECT month,employee,SUM(amount) amount 
FROM(
    SELECT m.month, e.employee, ISNULL(s.amount, 0) AS amount 
    FROM dbo.months AS m 
    CROSS JOIN (SELECT DISTINCT employee FROM dbo.sales) AS e 
    LEFT JOIN dbo.sales AS s 
    ON s.employee = e.employee 
    AND m.month = s.month 
)X 
GROUP BY month, employee 
+0

這不是聚集是什麼呢? – o365spo

+0

不,它不是。不知何故錯過了這個要求。更新了上面的代碼以包含此要求。 –

相關問題