按日期订购唯一帐户

时间:2014-12-27 00:32:35

标签: sql sql-server sql-server-2012

我有一张桌子:

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。

2 个答案:

答案 0 :(得分: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;

这会将年份和月份分成不同的列。如果你真的想要,可以将它们连接成一个值。

答案 1 :(得分:0)

使用month的{​​{1}}和year的{​​{1}}分组来跳过计算中的日期部分。在datecreated desc中使用相同的月份和年份。然后连接月份和年份以获得结果

order by

<强>结果

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