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

在输出中,我希望月份对应于 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 的提交日期开始。

4

2 回答 2

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]
于 2013-04-15T10:22:04.010 回答
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]
于 2013-04-15T10:38:50.870 回答