2

我需要运行一个报告,给出每个月具有特定创建项的记录计数。对于每个月,我的查询会多次显示该月。难道是我做错了什么:我的脚本:

Select DATEPART(mm,DatePrinted),COUNT(ReceiptNo)As CardPrinted
from mytble where ReceiptNo like'990%'
Group by DatePrinted    

可能的收据:800,75。
预计是这样的:

一月总数

二月总数等。

4

2 回答 2

3

Use Group by DATEPART(month,DatePrinted).

Select DATEPART(month,DatePrinted) As MyMonth, COUNT(ReceiptNo) As CardPrinted
From mytble 
Where ReceiptNo like '990%'
Group by DATEPART(month,DatePrinted)   

If you need name of the month, then use DATENAME() function:

Select DATENAME(month,DatePrinted) As MyMonth, COUNT(ReceiptNo) As CardPrinted
From mytble 
Where ReceiptNo like '990%'
Group by DATENAME(month,DatePrinted)  

Note: May be you need to group by year to get correct results. Otherwise, you will get the count of similar months regardless of the year. If you are looking for a particular year, add this filter to the WHERE clause Year(DatePrinted) = yourYear

于 2013-11-14T14:57:48.653 回答
3

您的 group by 语句是错误的,它必须在DATEPART(mm,DatePrinted)

SELECT DATEPART(mm, DatePrinted) AS [Month], COUNT(ReceiptNo) As CardPrinted
FROM mytble 
WHERE ReceiptNo LIKE '990%'
GROUP BY DATEPART(mm, DatePrinted)

您也可以替换COUNT(ReceiptNo)COUNT(*)

另请注意,就像现在一样,不同年份的所有月份都将组合在一起。

如果这不是你想要的行为,你SELECT可以GROUP BY DATEPART(yyyy, DatePrinted), DATEPART(mm, DatePrinted)

于 2013-11-14T14:58:26.640 回答