2

我的示例表结构是:

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

我的查询是:

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

我得到了一个结果:

TT         Posts
Mar-2013    1
Mar-2013    2
Sep-2012    1

但我想要一个结果:

TT         Posts
Mar-2013    3
Sep-2012    1

但我无法在我的查询中找到我的错误。谢谢。

4

2 回答 2

3

您是否尝试选择每个月的行和计数?

如果是这样 - 尝试这样的事情:

SELECT  
   YEAR(Testdate), MONTH(Testdate),
   COUNT(*) totalPost
FROM    
   tableName
GROUP BY
   YEAR(Testdate), MONTH(Testdate)

更新:如果您坚持在 SQL Server 内部进行格式化(我认为这样做是错误的地方......) - 然后使用这样的东西:

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)
于 2013-03-25T10:07:25.653 回答
2

你需要先DATETIME投入DATE

SELECT  CAST(TestDate AS DATE) DATE_ONLY,
        COUNT(*) totalPost
FROM    tableName
GROUP   BY  CAST(TestDate AS DATE)
于 2013-03-25T09:59:23.237 回答