按活动日期列出的SQL计数

按活动日期列出的SQL计数,sql,sql-server,Sql,Sql Server,如果我有一个记录表和活动/不活动日期,有没有一个简单的方法按月统计活动记录?例如: tbl_a id dt_active dt_inactive a 2013-01-01 2013-08-24 b 2013-01-01 2013-07-05 c 2012-02-01 2012-01-01 如果我必须按月份生成活动记录的输出,如下所示: 活动:dt_active

如果我有一个记录表和活动/不活动日期,有没有一个简单的方法按月统计活动记录?例如:

tbl_a
id        dt_active    dt_inactive
a         2013-01-01   2013-08-24
b         2013-01-01   2013-07-05
c         2012-02-01   2012-01-01
如果我必须按月份生成活动记录的输出,如下所示:
活动:dt_active<月初第一天这里有一种方法可以给出月初的活动计数。它创建所有月份的列表,然后将此信息加入
tbl\u a

with dates as (
      select cast('2013-01-01' as date) as month
      union all
      select dateadd(month, 1, dates.month)
      from dates
      where month < cast('2013-09-01' as date)
)
select convert(varchar(7), month, 121), count(a.id)
from dates m left outer join
     tbl_a a
     on m.month between a.dt_active and a.dt_inactive
group by convert(varchar(7), month, 121)
order by 1;

是一个处理工作查询的SQL工具。

这里有一个方法可以给出月初的活动计数。它创建所有月份的列表,然后将此信息加入
tbl\u a

with dates as (
      select cast('2013-01-01' as date) as month
      union all
      select dateadd(month, 1, dates.month)
      from dates
      where month < cast('2013-09-01' as date)
)
select convert(varchar(7), month, 121), count(a.id)
from dates m left outer join
     tbl_a a
     on m.month between a.dt_active and a.dt_inactive
group by convert(varchar(7), month, 121)
order by 1;

是一个SQL查询工具。

这很酷,谢谢。我不知道如何将
一起使用,正在上载一个表。这很酷,谢谢。我不知道如何将
一起使用,正在上载一个表。
on m.month >= a.dt_active and m.month < a.dt_inactive