2015-01-20 147 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關鍵字免除。