我无法获得一个sproc来给我这种类型的输出:
+-----------+------------------+ | Month | NoOfModifcations | +-----------+------------------+ | Jan 2008 | 5 | | Nov 2008 | 6 | | Feb 2010 | 20 | | Jul 2013 | 7 | +-----------+------------------+
到目前为止,我设法让输出看起来像这样,但我还没有设法让输出按年份排序,然后是月份 - 它按字母顺序排列。这是我到目前为止所拥有的:
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))
我确实在日期时间字段上尝试了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.
将日期时间转换/选择/分组到字符串也非常混乱。那里的任何建议也会非常有帮助!
提前致谢!
答案 0 :(得分:2)
这应该做:
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)
答案 1 :(得分:2)
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)
保持简单,并在C#代码或报告中进行连接......
答案 2 :(得分:1)
使用此选项将varchar转换为datetime
SELECT CONVERT(Datetime,'Jan 2008 ')
然后根据日期时间desc对列进行排序。 对不起,简短而未完成的答案,希望它有所帮助。