计算不同时期的计数(id)

时间:2014-09-19 19:38:09

标签: sql sql-server

我有以下查询,允许我存储一组月份的开始日期和日期

DECLARE @Month nvarchar(max)
DECLARE @Year int, @startDate as datetime

set @Month = ('5,11,12')
set @Year = 2014

 SELECT  Value , DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t  ,DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))), -1)as t1
INTO TempWeek
FROM dbo.SplitString(@Month,',')

我得到了以下结果

Value  t                      t1
5   2014-05-01 00:00:00.000 2014-05-31 00:00:00.000
11  2014-11-01 00:00:00.000 2014-11-30 00:00:00.000
12  2014-12-01 00:00:00.000 2014-12-31 00:00:00.000

我有以下查询,我可以计算(id)

SELECT count(DISTINCT ID)
 FROM 
  test EF 
  WHERE cond BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 00:00:00'

我的问题是如何将两个查询合并,以便为t中存储的每个t1TempWeek重新处理上述处理?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以执行joingroup by

SELECT tempweek.t, tempweek.t1, count(DISTINCT ID)
FROM (SELECT Value, DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t,
            DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month, Value-1,DATEADD(year, @Year-1900,0))), -1) as t1
      FROM dbo.SplitString(@Month, ',')
     ) tempweek left join
     test EF
     on cond BETWEEN tempweek.t AND tempweek.t1
GROUP BY tempweek.t, tempweek.t1;

答案 1 :(得分:1)

我认为你可以将你的第一个查询包装在一个公共表表达式中,如下所示:

;WITH cte AS (
    SELECT 
      Value, 
      DATEADD(month,Value-1,DATEADD(year,@Year-1900,0)) as t,
      DATEADD(month, ((YEAR(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))) - 1900) * 12) + MONTH(DATEADD(month,Value-1,DATEADD(year,@Year-1900,0))), -1)as t1
    FROM dbo.SplitString(@Month,',')
)
SELECT T, T1, COUNT(DISTINCT ID)
FROM test EF, cte
WHERE cond BETWEEN t AND t1
GROUP BY T, T1