我有一个名为Worked_Received的表。
列
Received Date Ticket number
12/08/2014 2135823
13/09/2014 2458956
01/02/2014 2458796
03/07/2014 2456353
04/07/2014 2457896
我想得到像这样的结果
Month Count
August 1
September 1
February 1
July 2
答案 0 :(得分:2)
你可以这样做:
SELECT
COUNT(*) AS [Count],
DATENAME(month,table1.[Received Date]) AS [Month]
FROM
table1
GROUP BY
DATENAME(month,table1.[Received Date])
<强>更新强>
某些日期无法转换为日期时间。如果您知道varchar将始终具有相同的格式。您可以像这样使用转换:
SELECT
COUNT(*) AS [Count],
DATENAME(month,CONVERT(datetime,table1.[Received Date], 103)) AS [Month]
FROM
table1
GROUP BY
DATENAME(month,CONVERT(datetime,table1.[Received Date], 103))
更新2
示例数据中的所有日期都会毫无例外地转换为:
INSERT INTO @tbl VALUES('12/08/2014'),('13/09/2014'),('01/02/2014'),
('03/07/2014'),
('04/07/2014')
SELECT
DATENAME(month,CONVERT(datetime, tbl.date, 103))
FROM
@tbl AS tbl
您获得的转换错误是因为存在无法转换为日期的varchar。要找出哪一行没有转换,您可以查看:
SELECT
*
FROM
table1
WHERE ISDATE(table1.[Received Date])=0
参考: