2014-12-27 28 views
0

我有一個表:爲了唯一帳戶按日期

create table remote (account int ,datecreated datetime,status int) 
insert into remote (account , datecreated,status) 
values 

(123,'2015-08-25',1), 
(123,'2015-08-25',1), 
(123,'2015-09-26',1), 
(1238,'2015-08-25',1), 

(123,'2014-08-25',1), 
(123,'2014-08-26',1), 
(1238,'2014-08-25',1), 
(1238,'2014-08-25',1), 
(1235,'2014-08-25',1), 

(1234,'2014-09-22',1), 
(1234,'2014-09-22',1), 

(1234,'2014-10-29',1), 
(1236,'2014-10-25',1); 

在這裏,我想獲得的唯一的帳戶數每個月/年,其中狀態= 1 例如使用上面的數據:

輸出將

count | month 
------------- 
1  |9/2015 
2  |8/2015 
2  |10/2014 
1  |9/2014 
3  |8/2014 

我怎樣才能使這項工作?

我使用SQL 2012

回答

0

使用組monthyeardatecreated跳過天的部分在計數。在order by desc中使用相同的月份和年份。然後拼接月份和年份來得到結果

SELECT [Count], 
     [Mon/Year]= CONVERT(VARCHAR(2), [Month]) + '/' + CONVERT(VARCHAR(4), [year]) 
FROM (SELECT [year]=Year(datecreated), 
       [month]= Month(datecreated), 
       [Count]= Count(distinct account) 
     FROM remote 
     GROUP BY Year(datecreated), 
       Month(datecreated)) a 
ORDER BY [year] DESC,[Month] DESC 

結果

Count Mon/Year 
----- -------- 
1  9/2015 
3  8/2015 
2  10/2014 
1  9/2014 
5  8/2014 
+0

從上面的數據應該只有1 9/2014 ,因爲它有相同的帳號,http://sqlfiddle.com/#!6/3f5db/1 – jfishbow

+0

@jfishbow更新檢查現在http://sqlfiddle.com /#!6/3f5db/2 –

0

這是一個group by查詢與過濾器和一些日期時間邏輯:

select year(datecreated) as yr, month(datecreated) as mon, count(*) 
from remote 
where status = 1 
group by year(datecreated), month(datecreated) 
order by yr desc, mon desc; 

這使年份和月份成單獨的列。如果您真的想要,可以將它們連接在一起成爲一個單一的值。

+0

@RyanVincent。 。 。謝謝。 –