我需要根据&amp ;;显示过去12个月的工作申请数。需要根据工作申请日期对他们进行分组
我尝试按照它生成错误,如下所示。
SELECT
COUNT(MONTH(ApplicationDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ApplicationDate) AS VARCHAR(4)) AS Total,
ApplicationDate
FROM
[Jobs]
GROUP BY
ApplicationDate, ApplicationDate
ORDER BY
ApplicationDate
但这导致了一个错误:
Msg 195,Level 15,State 10,Line 9
'COUNT'不是公认的内置函数名称。
我需要它用于SQL Server 2008
最终工作解决方案
SELECT
MONTH(ApplicationDate), YEAR(ApplicationDate), COUNT(*) AS Total,
(CAST(MONTH(ApplicationDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ApplicationDate) AS VARCHAR(4))) as ApplicationDate
FROM [Jobs]
GROUP BY YEAR(ApplicationDate), MONTH(ApplicationDate)
ORDER BY
YEAR(ApplicationDate), MONTH(ApplicationDate)
答案 0 :(得分:1)
你需要尝试这样的事情,每个月/每年获得一行,其中包含该月/年的应用数量:
SELECT
MONTH(ApplicationDate),
YEAR(ApplicationDate),
COUNT(*)
FROM
dbo.[Jobs]
GROUP BY
YEAR(ApplicationDate),
MONTH(ApplicationDate)
ORDER BY
YEAR(ApplicationDate),
MONTH(ApplicationDate)
这也计算每月/每年的应用程序和组。你应该得到这样的输出:
(这取自AdventureWorks
示例数据库)
如果您执行了GROUP BY ApplicationDate
,那么您基本上按实际的日期本身进行分组/计数(不是它的月/年部分)
更新:如果您必须让SQL Server提供MM-YYYY
格式的格式(真的应该在您的网络应用中完成,而不是由SQL Server完成) ),然后试试这个:
;WITH GroupedData AS
(
SELECT
DateMonth = MONTH(ApplicationDate),
DateYear = YEAR(ApplicationDate),
JobsCount = COUNT(*)
FROM
dbo.[Jobs]
GROUP BY
YEAR(ApplicationDate),
MONTH(ApplicationDate)
)
SELECT
RIGHT('00' + CAST(DateMonth AS VARCHAR(2)), 2) + '-' +
CAST(DateYear AS VARCHAR(4)),
JobsCount
FROM
GroupedData
ORDER BY
DateMonth, DateYear
答案 1 :(得分:0)
这个怎么样?
SELECT
COUNT(*) AS Total,
(CAST(MONTH(ApplicationDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ApplicationDate) AS VARCHAR(4))) as ApplicationDate
FROM
[Jobs]
GROUP BY
(CAST(MONTH(ApplicationDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ApplicationDate) AS VARCHAR(4)))
ORDER BY
ApplicationDate
一个月失去了演员表演功能。输出如下。
Total ApplicationDate
22217 7-2012
17979 8-2012
30341 9-2012
编辑排序......
如果您不特别关注'MM-YYYY'格式。将月/年组合转换为数字和顺序。试试这个。
SELECT
COUNT(*) AS Total,
RIGHT(CONVERT(VARCHAR(10), ApplicationDate, 103), 7) as ApplicationDate,
CAST(REPLACE(RIGHT(CONVERT(VARCHAR(10), ApplicationDate, 103), 7), '/', '') as int) as numdate
FROM
[Jobs]
GROUP BY
RIGHT(CONVERT(VARCHAR(10), ApplicationDate, 103), 7)
ORDER BY
numdate,ApplicationDate
答案 2 :(得分:0)
试试这个...
SELECT DATENAME(month,ApplicationDate) + ' ' + CAST(DATEPART(year,ApplicationDate) AS VARCHAR(4)),
COUNT(1) TotalCnt
FROM dbo.[Jobs]
GROUP BY DATENAME(month,ApplicationDate) + ' ' + CAST(DATEPART(year,ApplicationDate) AS VARCHAR(4))