T-SQL按月分组获取今年的记录

时间:2016-06-29 08:10:54

标签: sql-server tsql

我有一个看起来像这样的数据表

ID        CreatedDate   
A123      2015-01-01  
B124      2016-01-02  
A125      2016-01-03  
A126      2016-01-04

我想做的是今年仅按月(以文字为单位)。我有一些以下查询,但它返回的所有年份的数据不仅仅是这一个:

 Select Count(ID), DateName(month,createddate) from table
 Where (DatePart(year,createddate)=datepart(year,getdate())
 Group by DateName(month,createddate)

返回

Count    CreatedDate
4        January

而不是

Count    CreatedDate
3        January

我哪里出错了?我确定将日期转换为出错的月份是有意义的

2 个答案:

答案 0 :(得分:1)

刚刚测试过你的代码:

;WITH [table] AS (
SELECT *
FROM (VALUES
('A123',      '2015-01-01'),
('B124',      '2016-01-02'),
('A125',      '2016-01-03'),
('A126',      '2016-01-04')
) as t(ID, CreatedDate)
)

SELECT  COUNT(ID), 
        DATENAME(month,CreatedDate) 
FROM [table]
WHERE DATEPART(year,CreatedDate)=DATEPART(year,getdate())
GROUP BY DATENAME(month,CreatedDate)

输出

3   January

我删除了(附近的WHERE

答案 1 :(得分:0)

 select count(id) as Count,
 case when month(createddate)=1 THEN 'Januray' END as CreatedDate
 from [table]
 --where year(createddate)=2016 optional if you only want the 2016 count
 group by month(createddate),year(createdDate)