Sql 如何按月份和年份获取唯一id计数?

Sql 如何按月份和年份获取唯一id计数?,sql,Sql,我有一个查询正在计算用户的总id 但我希望它能得到每个月/年的计数 使用“开始日期”列 start_date是agentdispodetail和datetype中的同谋 开始日期通常如下所示: 2014-11-21 14:47:15.680 select distinct user_id, count(*) as total_id from agentdispodetail group by user_id 我使用sql 2012。你说的是 select user_id, year(

我有一个查询正在计算用户的总id 但我希望它能得到每个月/年的计数 使用“开始日期”列

start_date是agentdispodetail和datetype中的同谋

开始日期通常如下所示: 2014-11-21 14:47:15.680

select distinct user_id, count(*) as total_id
  from agentdispodetail
  group by  user_id
我使用sql 2012。

你说的是

select user_id, year(start_date), month(start_date), count(*) as total_id
from agentdispodetail
group by user_id, year(start_date), month(start_date)
order by user_id, year(start_date), month(start_date)
select year  = datepart(  year  ,start_date  ) ,
       month = datepart( month , start_date ) ,
       N     = count( distinct user_id )
from ...
where ...
group by datepart( year  , start_date ) ,
         datepart( month , start_date )
order by 1,2
另一种技术使用了一些日期算法:

select start_date = dateadd(day ,
                      1-datepart(day,start_date) ,
                      convert(date,start_date)
                      ) ,
       N          = count( distinct user_id )
from ...
where ...
group by dateadd(day, 1-datepart(day,start_date) , convert(date,start_date) )
order by 1

如果表架构将列
user\u id
作为唯一列-它是表的主键或具有唯一索引-您可以省去
distinct
关键字。

什么是开始日期?一列agentdispodetail?我认为OP可能只是要求计算该月/年的记录数,在这种情况下,应该取出用户id。除此之外。回答得好。