简体   繁体   English

计算日期时间每个月内的行数,按年份月份分组

[英]Count number of rows within each month of a datetime, group by year month

I'm having trouble getting a sproc to give me this type of output: 我很难得到一个存储程序来给我这种类型的输出:

+-----------+------------------+
|   Month   | NoOfModifcations |
+-----------+------------------+
| Jan  2008 |                5 |
| Nov  2008 |                6 |
| Feb  2010 |               20 |
| Jul  2013 |                7 |
+-----------+------------------+

So far i managed to get the output to look like this, but i haven't yet managed to get the output to be sorted by year, then month - it's going alphabetically. 到目前为止,我设法使输出看起来像这样,但是我还没有设法使输出按年然后按月排序-这是按字母顺序进行的。 Here's what i have so far: 这是我到目前为止的内容:

SELECT convert(varchar(4), YEAR(LastModifedDate)) + ' ' + convert(varchar(3),datename(month, LastModifedDate)) as Dates,
    count(*) as Number

FROM aims.Modification

WHERE CompanyID = @companyID 
    AND LastModifedDate >= DATEADD(month, @numberOfMonths * -1, GETDATE())

GROUP BY convert(varchar(4), YEAR(LastModifedDate)) + ' ' + convert(varchar(3),datename(month, LastModifedDate))

I did try an ORDER BY on the datetime field but got: 我确实在datetime字段上尝试了ORDER BY,但得到了:

Column "aims.Modification.LastModifedDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

It's also very messy on converting/selecting/group by on the datetime to string. 在日期时间上转换/选择/分组依据也很麻烦。 Any advice there would also be very helpful! 那里的任何建议也将非常有帮助!

Thanks in advance! 提前致谢!

This should do: 应该这样做:

SELECT  CONVERT(VARCHAR(4),YEAR(LastModifedDate)) + ' ' + 
        CONVERT(VARCHAR(3),DATENAME(MONTH,LastModifedDate)) AS Dates,
        COUNT(*) as Number
FROM aims.Modification
WHERE CompanyID = @companyID 
    AND LastModifedDate >= DATEADD(MONTH,@numberOfMonths * -1,GETDATE())
GROUP BY CONVERT(VARCHAR(4),YEAR(LastModifedDate)) + ' ' + 
         CONVERT(VARCHAR(3),DATENAME(MONTH,LastModifedDate)),
         CONVERT(VARCHAR(6),LastModifedDate,112)
ORDER BY CONVERT(VARCHAR(6),LastModifedDate,112)
SELECT YEAR(LastModifedDate), MONTH(month) as Dates, count(*) as Number
FROM aims.Modification
WHERE CompanyID = @companyID 
    AND LastModifedDate >= DATEADD(month, @numberOfMonths * -1, GETDATE())
GROUP BY YEAR(LastModifedDate), MONTH(LastModifiedDate)
ORDER BY YEAR(LastModifedDate), MONTH(LastModifiedDate)

Keep it simple and make the concatenation in your C# code or report... 保持简单,并在您的C#代码或报告中进行串联...

Use this to convert your varchar to datetime 使用此将您的varchar转换为datetime

 SELECT CONVERT(Datetime,'Jan  2008 ')  

Then sort your column based upon datetime desc. 然后根据datetime desc对列进行排序。 Sorry for short and unfinished answer, Hope it helps. 对不起,我们还没有完成一个简短的答案,希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM