我正在寻找T-SQL中的一种方法,以便在数月和数年内获得不同类型成员的数量。我的表:
+-------------+-----------+------------
| Member_type | Join_date | End_date |
+-------------+-----------+------------+
| TYPE1 | 12-Nov-07 | 12/11/2015 |
| TYPE2 | 24-Nov-10 | 07/07/2016 |
| TYPE3 | 29-Apr-08 | 28/04/2009 |
| TYPE2 | 28-Apr-06 | 31/03/2007 |
| TYPE1 | 11-Jul-06 | 30/06/2007 |
| TYPE2 | 13-Mar-08 | 12/06/2011 |
+-------------+-----------+------------+
我正在寻找像这样的结果
+-------------+--------+--------+--------+--------+
| Member_type | Jan-15 | Feb-15 | Mar-15 | Apr-15 |
+-------------+--------+--------+--------+--------+
| TYPE1 | 1 | 5 | 4 | 2 |
| TYPE2 | 6 | 4 | 2 | 1 |
| TYPE3 | 5 | 6 | 7 | 8 |
+-------------+--------+--------+--------+--------+
显示近年来在1月,2月等期间给定类型的成员总数。 (那些加入的人 - 那些离开的人)
到目前为止,我已经到了这个
SELECT COUNT("membership_type") AS JANUARY2015
FROM "dbo"."Data" T0
WHERE (join_date < DATEADD(month, -2, GETDATE()))
AND (join_date > GETDATE())
GROUP BY T0."membership_type" ;
答案 0 :(得分:1)
SELECT Member_type
, COUNT(CASE WHEN YEAR(join_date) = 2015 AND MONTH(join_date) = 1 THEN 1 END) AS [Jan-15]
, COUNT(CASE WHEN YEAR(join_date) = 2015 AND MONTH(join_date) = 2 THEN 1 END) AS [Feb-15]
, COUNT(CASE WHEN YEAR(join_date) = 2015 AND MONTH(join_date) = 3 THEN 1 END) AS [Mar-15]
, COUNT(CASE WHEN YEAR(join_date) = 2015 AND MONTH(join_date) = 4 THEN 1 END) AS [Apr-15]
...
FROM MarketingData
GROUP BY Member_type