以下语句可以实现查询出动态时间段内每周的数据记录数,且得到的结果显示如下:
周期    记录数
1         50
2         35
3         100
4         67
............set datefirst 1  
select datepart(wk,CAST(txtime AS DATETIME)) as 周,count(1) as 记录数
from qxzb
where CAST(txtime AS DATETIME)>='2011-01-01' and CAST(txtime AS DATETIME)<'2011-6-21'
group by datepart(wk,CAST(txtime AS DATETIME))
现要实现查询出动态时间段内每月的数据记录数(需自动识别每月的天数,如2月份从1日至28日),且显示格式如下,请问如何修改?
周期    记录数
1         200
2         135
3         100
4         167
.............

解决方案 »

  1.   

    set datefirst 1   
    select 
    DATEPART(MM,CAST(txtime AS DATETIME)) AS '月',datepart(wk,CAST(txtime AS DATETIME)) as 周,count(1) as 记录数
    from qxzb
    where CAST(txtime AS DATETIME)>='2011-01-01' and CAST(txtime AS DATETIME)<'2011-6-21'
    group by datepart(wk,CAST(txtime AS DATETIME)),DATEPART(MM,CAST(txtime AS DATETIME))
      

  2.   

    select convert(varchar(7),txtime,120) 月,count(1) 记录数
    from qxzb
    where CAST(txtime AS DATETIME)>='2011-01-01' and CAST(txtime AS DATETIME)<'2011-6-21'
    group by convert(varchar(7),txtime,120)