I have a date field in a query and I do want to get GROUP BY report like this:

DATE    COUNT
2010-01  10
2010-02  2
...
2010-12  24
2012-13  34

What is the proper syntax to obtain this on SQL Server?

有帮助吗?

解决方案

All these conversions to string work, but I find this method more efficient, albeit less readable:

SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0), COUNT(*)
  FROM dbo.TheTable
  GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0); 

If you don't want to repeat the expression, then:

;WITH x AS (SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0)
  FROM dbo.TheTable)
SELECT m, COUNT(*)
  FROM x GROUP BY m;

This way the output is still a date/time value and can be used that way for other things. And it doesn't involve any messy string conversions.

其他提示

 CONVERT(VARCHAR(7), CreationDate, 120) as Date

You can simply do:

select convert(char(7), @myDate, 20)

Example

declare @myDate as DateTime
set @myDate = '2012-06-23'
select convert(char(7), @myDate, 20)

Output

-------
2012-06

So the full statement would look like:

select convert(char(7), myDate, 20), count(*) as Count
from MyTable
group by convert(char(7), myDate, 20)

Update

The sample data includes the value 2012-13. I am going to assume this is a typo and that the number after the dash represents the month.

SELECT CAST(DATEPART(year, dateCol) as VARCHAR) + '-' + CAST(DATEPART(month, dateCol) as VARCHAR) as Date, count(*) As Count
FROM myTable
GROUP BY CAST(DATEPART(year, dateCol) as VARCHAR) + '-' + CAST(DATEPART(month, dateCol) as VARCHAR)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top