0

我有一个 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               |

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

4

3 回答 3

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)
于 2013-03-12T10:45:02.953 回答
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)
于 2013-03-12T10:44:53.660 回答
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)
于 2013-03-12T10:47:46.373 回答