按月分组子句问题

时间:2013-03-12 10:42:23

标签: sql sql-server date group-by

我有一个SQL查询来按月添加到系统中的许多产品进行分组。我上周运行了这个查询,今天再次运行它。今天结果似乎有不同的顺序。是否可以运行此查询并显示月份的第二列?

这是我的原始查询:

SELECT COUNT(*)
FROM dbo.Products p
WHERE YEAR(t.CreatedDate) = '2013' 
  AND t.Deleted = 0 
  AND t.RemovedFromSale = 0
GROUP BY MONTH(t.CreatedDate)

返回以下内容:

 | (No Column Name)
1| 2009
2| 161
3| 98

理想情况下,我想要这样的事情:

 | (No Column Name) | Month Name
1| 2009             |  
2| 161              |
3| 98               |

这可以通过改变我的查询来实现吗?

3 个答案:

答案 0 :(得分:4)

如果您想要退回MONTH(t.CreatedDate),则需要在SELECT列表中添加该列:

SELECT COUNT(*) as Total,
  MONTH(t.CreatedDate) as Month
FROM dbo.Products p
WHERE YEAR(t.CreatedDate) = '2013' 
  AND t.Deleted = 0 
  AND t.RemovedFromSale = 0
GROUP BY MONTH(t.CreatedDate)

MONTH()将月份作为整数返回。如果您想以月份的名称返回月份,那么您将需要使用DATENAME()

SELECT COUNT(*) as Total,
  DATENAME(month, t.CreatedDate) as Month
FROM dbo.Products p
WHERE YEAR(t.CreatedDate) = '2013' 
  AND t.Deleted = 0 
  AND t.RemovedFromSale = 0
GROUP BY DATENAME(month, t.CreatedDate)

答案 1 :(得分:2)

将SQL更改为

SELECT COUNT(*), MONTH(t.CreatedDate)
  FROM dbo.Products p
  WHERE YEAR(t.CreatedDate) = '2013' AND t.Deleted = 0 AND t.RemovedFromSale = 0
  GROUP BY MONTH(t.CreatedDate)

答案 2 :(得分:1)

尝试:

SELECT 
    COUNT(*), DATENAME(m, CreatedDate) [MonthName]
FROM dbo.Products p
WHERE YEAR(t.CreatedDate) = '2013' AND t.Deleted = 0 AND t.RemovedFromSale = 0
GROUP BY DATENAME(m, CreatedDate)