Sql server T-SQL按月份分组获取今年的记录
我有一个数据表,看起来像这样Sql server T-SQL按月份分组获取今年的记录,sql-server,tsql,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 Whe
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
我哪里出错了?我确信这与将日期转换为出错的月份有关刚刚测试了您的代码:
;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
我删除了
(
nearWHERE
该问题不可再现,至少在我这方面不可再现。您对发布的样本数据(1月3日)查询的结果与您想要的结果完全一致。看起来这是对的,一定是我在表中的初始数据中出错了
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)