2015-01-20 150 views
-1

我有一个计算总USER_ID 查询,但我想它得到计数使用列起始日期每个月/年 的。如何按月份和年份获得唯一的ID计数?

起始日期是agentdispodetail和datetype一个collumn。

起始日期通常是这样的: 2014年11月21日14:47:15.680

select distinct user_id, count(*) as total_id 
    from agentdispodetail 
    group by user_id 

我使用SQL 2012

+0

什么是start_date?一列agentdispodetail? – ASh 2015-01-20 19:47:30

回答

1
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) 
+1

我想OP可能只是要求一个月/年的记录数,在这种情况下user_id应该被取出。除此之外。好答案。 – DaaaahWhoosh 2015-01-20 19:54:50

0

你这样说

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_id —您可以用distinct关键字免除。