重开贴:这个sql语句如何写

数据表aa里有10000条数据记录,表中有一字段为“数据录入日期”(数据录入日期从2010年11月1日至2011年5月30日,请问想通过一条sql语句查询出每个月的记录数,这个sql语句如何写(得出的结果是每个月都有一个数,如下表)

 数据录入日期:2010-11 2010-12 2011-01 2011-02 2011-03 ....
  记录数 500 1000 1500 2000 1400

作者: tdzhz3   发布时间: 2011-06-10

SQL code

create table #t_test(dt datetime)
insert into #t_test(dt)
select '2010-11-01'
union all
select '2010-11-05'
union
select '2010-12-01'
union 
select '2011-05-30'
union
select '2011-05-01'

select sum(case when convert(varchar(7),dt,120) = '2010-11' then 1 else 0 end) as y201011,
sum(case when convert(varchar(7),dt,120) = '2010-12' then 1 else 0 end) as y201012,
sum(case when convert(varchar(7),dt,120) = '2011-01' then 1 else 0 end) as y201101,
sum(case when convert(varchar(7),dt,120) = '2011-02' then 1 else 0 end) as y201102,
sum(case when convert(varchar(7),dt,120) = '2011-03' then 1 else 0 end) as y201103,
sum(case when convert(varchar(7),dt,120) = '2011-04' then 1 else 0 end) as y201104,
sum(case when convert(varchar(7),dt,120) = '2011-05' then 1 else 0 end) as y201105
from #t_test


作者: jyh070207   发布时间: 2011-06-10

我觉得二楼指定日期没意义.楼主的月份不固定不可能都去指定月份.我认为.datepart取出月份.然后通过月份查找记录数会好一些,也快一些.

作者: chirea   发布时间: 2011-06-10

SQL code
--不知道理解的对不对
select select convert(varchar(7),getdate(),120) as 月份,sum(记录数) as 每月记录数
from tb
group by select convert(varchar(7),getdate(),120)

作者: cd731107   发布时间: 2011-06-10

引用 3 楼 cd731107 的回复:

SQL code
--不知道理解的对不对
select select convert(varchar(7),getdate(),120) as 月份,sum(记录数) as 每月记录数
from tb
group by select convert(varchar(7),getdate(),120)

SQL code

select convert(varchar(7),getdate(),120) as 月份,sum(记录数) as 每月记录数
from tb
group by convert(varchar(7),getdate(),120)


貌似豆子多些了两个select

作者: maco_wang   发布时间: 2011-06-10

SQL code
 select convert(varchar(7),dt,120),count(*) as 记录数
 from aa
 group by convert(varchar(7),dt,120)

作者: abcjun188   发布时间: 2011-06-10