2013-04-15 24 views
0

在這裏,我要解釋一下我的情況:分岔記錄各自到幾個月

我有如下表:

Table : Service_Type 

Id | Service_Name | Service_Table_Name| 
---------------------------------------- 
1 | FA   | FA  | 
2 | TPA  |  TPA  | 


Table: Service_Mapping 

Id | Service_Type_Id | 
--------------------------- 
1 | 1  | 
2 | 2  | 
3 | 2  | 
4 | 1  | 

Table: FA 

Id | Created_date| Qty | 
----------------------------- 
1 | 3/20/2012 | 20 | 
2 | 4/22/2012 | 10 | 
3 | 5/12/2012 | 15 | 
4 | 6/3/2012 | 5 | 

Table: TPA 

Id | Created_date| Qty | 
----------------------------- 
1 | 5/20/2012 | 2 | 
2 | 7/22/2012 | 10 | 
3 | 1/12/2012 | 1 | 
4 | 9/3/2012 | 5 | 

我想這樣的輸出:

Month | FA| TPA| 
---------------- 
Jan  0 1 
Mar  1 0 
Apr  1 0 
Jul  1 0 
Sep  0 1 

在輸出I要月份到FA和TPA表的Created_date字段。並分別到月份我想總和多少FA和TPA發生在一個月內。

我得到的輸出喜歡

FA | TPA | 
-------------- 
3 | 2 | 

SELECT 
SUM(CASE WHEN Service_Type_Id = 1 THEN 1 ELSE 0 END) AS FA, 
SUM(CASE WHEN Service_Type_Id = 2 THEN 1 ELSE 0 END) AS TPA 
FROM Service_Mapping 

,但現在我想分叉他們各自對他們發生個月。從TPA和FA的日期提交。

回答

0

試試這個:

SELECT Mon.monthNAME, ISNULL(TPAcount,0) TPAcount, ISNULL(FAcount,0) FAcount FROM 
(
    SELECT DATENAME(MONTH,created_date) AS [monthNAME], MONTH(created_date) [month], YEAR(created_date) as [year] FROM FA 
    UNION 
    SELECT DATENAME(MONTH,created_date) AS [monthNAME], MONTH(created_date) [month], YEAR(created_date) as [year] FROM TPA 
) Mon LEFT JOIN 
(
    SELECT DATENAME(MONTH,created_date) tpaMonth, YEAR(created_date) as [year] , COUNT(1) TPAcount 
    FROM TPA GROUP BY DATENAME(MONTH,created_date), YEAR(created_date) 
) TPA ON TPA.tpaMonth = Mon.monthNAME and tpa.[year] = mon.[year] LEFT JOIN 
(
    SELECT DATENAME(MONTH,created_date) faMonth, YEAR(created_date) as [year] , COUNT(1) FAcount 
    FROM FA GROUP BY DATENAME(MONTH,created_date), YEAR(created_date) 
) FA ON FA.faMonth = MON.monthNAME and FA.[year] = mon.[year] 

ORDER BY 
Mon.[year], Mon.[month] 
+0

我不知道爲什麼它顯示我此錯誤消息.......錯誤信息: 'Mon.month'不是公認的日期名稱選項。 –

+0

我不知道爲什麼它不起作用在您的網站。我創建了相同的表格,因爲它對我來說工作正常。你有沒有試過我的兩個查詢? – Konza

0

您還可以查看另一種方法:

SELECT Mon.monthNAME, SUM(tpCount) tpCount, SUM(faCount) faCount FROM 
(
    SELECT DATENAME(MONTH,created_date) AS [monthNAME], MONTH(created_date) [month], YEAR(created_date) as [year], 0 AS tpCount, 1 as faCount FROM FA 
    UNION 
    SELECT DATENAME(MONTH,created_date) AS [monthNAME], MONTH(created_date) [month], YEAR(created_date) as [year], 1 as tpCount, 0 AS faCount FROM TPA 
) Mon 
GROUP BY 
    [monthNAME],[month],[year] 
ORDER BY 
    Mon.[year], Mon.[month] 
+0

此查詢正常工作。但現在如果我添加更多的服務,例如。 FA,TPA,Gift,AA等等。然後我需要做些什麼改變? –

+0

您必須添加下一個聯合並向當前選擇添加新列。例如,如果您想要添加GIFT表,則必須在當前選擇中添加0作爲GiftCount,然後按如下所示添加下一個聯合:SELECT DATENAME(MONTH,created_date)AS [monthNAME],MONTH(created_date)[month],YEAR (created_date)as [year],0 as tpCount,0 AS faCount,1 as GiftCount FROM Gift – Konza