My sample table structure is:
TestDate
----------------------
2013-03-25 14:26:40.830
2013-03-20 13:37:39.763
2012-09-10 14:55:55.667
2013-03-20 13:33:20.480
And my query is :
SELECT DISTINCT
REPLACE(RIGHT(CONVERT(VARCHAR(20), TestDate, 106), 8), ' ', '-') AS TT
,(SELECT COUNT(*)
FROM Test bp
WHERE
CONVERT(VARCHAR(20), p.TestDate, 6) = CONVERT(VARCHAR(20), bp.TestDate, 6)) AS Posts
FROM Test p
I got a result:
TT Posts
Mar-2013 1
Mar-2013 2
Sep-2012 1
But I want a result:
TT Posts
Mar-2013 3
Sep-2012 1
But I am unable to find my mistake in my query. Thanks.
Are you trying to select the rows and count for each month?
If so - try something like this:
SELECT
YEAR(Testdate), MONTH(Testdate),
COUNT(*) totalPost
FROM
tableName
GROUP BY
YEAR(Testdate), MONTH(Testdate)
Update: if you insist on formatting that inside SQL Server (which I think is the wrong place to do this...) - then use something like this:
SELECT DISTINCT
SUBSTRING(DATENAME(MONTH, TestDate), 1, 3) + '-' + CAST(YEAR(TestDate) AS VARCHAR(4)),
YEAR(Testdate), MONTH(Testdate),
TotalPosts = COUNT(*)
FROM
tableName
GROUP BY
SUBSTRING(DATENAME(MONTH, TestDate), 1, 3) + '-' + CAST(YEAR(TestDate) AS VARCHAR(4)),
YEAR(Testdate), MONTH(Testdate)
ORDER BY
YEAR(Testdate), MONTH(Testdate)
You need to cast DATETIME
into DATE
first.
SELECT CAST(TestDate AS DATE) DATE_ONLY,
COUNT(*) totalPost
FROM tableName
GROUP BY CAST(TestDate AS DATE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.