我想算一下。不确定我是否可以使用count函数或使用case语句。
如果EndDate_YYYYMM> = StartDate_YYYYMM
,我想计算一个ID,但每个月计算一次ID例如:
ID StartDate_YYYYMM EndDate_YYYYMM
1 201601 201606
期望的结果:"参与"
StartDate_YYYYMM Count
201601 1
201602 1
201603 1
201604 1
201605 1
201606 1
201607
答案 0 :(得分:2)
这并不像你可能期待的那样简单明了。这主要是由于您的问题存在一些问题,其中包括:
VARCHAR
。话虽如此,鉴于我的理解是正确的,以下查询将产生您的目标结果:
;
WITH CTE_DateTable
AS (
SELECT #t.ID,
CAST(#t.StartDate_YYYYMM + '01' AS DATE) AS StartDate,
CAST(#t.EndDate_YYYYMM + '01' AS DATE) AS EndDate
FROM #t
),
CTE_MinMaxDates
AS (
SELECT MIN(CTE_DateTable.StartDate) AS MinDate,
MAX(CTE_DateTable.EndDate) AS MaxDate,
DATEDIFF(MONTH, MIN(CTE_DateTable.StartDate), MAX(CTE_DateTable.EndDate)) AS Difference
FROM CTE_DateTable
),
CTE_Nums
AS (
SELECT ROW_NUMBER() OVER (ORDER BY ob.object_id) AS Num
FROM sys.all_objects AS ob
),
CTE_Months
AS (
SELECT DATEADD(MONTH, n.Num - 1, d.MinDate) AS MonthStart
FROM CTE_MinMaxDates d
CROSS JOIN CTE_Nums n
WHERE DATEADD(MONTH, n.Num - 1, d.MinDate) <= d.MaxDate
)
SELECT CAST(DATEPART(YEAR, m.MonthStart) AS VARCHAR) + SUBSTRING(CONVERT(NVARCHAR(6), m.MonthStart, 112), 5, 2) AS StartDate_YYYYMM,
COUNT(DISTINCT d.ID) AS Count
FROM CTE_DateTable AS d
INNER JOIN CTE_Months AS m ON m.MonthStart BETWEEN d.StartDate AND d.EndDate
GROUP BY m.MonthStart;
答案 1 :(得分:0)
如果我已正确理解您的问题,那么您要查找的脚本是:
SELECT tab.StartDate_YYYYMM
, COUNT(*) AS [Count]
FROM YourTable tab
WHERE EndDate_YYYYMM >= StartDate_YYYYMM
GROUP BY tab.id
, tab.StartDate_YYYYMM