将SQL数据拆分为几个月

Mat*_*att 3 sql t-sql sql-server-2008

我今年有一个数百行,数百行.(MS SqlServer 2k8)

我想将此数据集拆分为客户查询/月.

到目前为止我所拥有的是什么;

Select count(id) As Customers, DatePart(month, enquiryDate) as MonthTotal, productCode From customerEnquiries
where enquiryDate > '2012-01-01 00:00:00'
group by productCode, enquiryDate
Run Code Online (Sandbox Code Playgroud)

但是这会为每个数据项生成一行.(而我希望每个数据项每月都有一行.)

那么我该如何更改上面的查询,以便而不是获取

1 1 10
1 1 10
1 1 11
1 2 10
1 2 10
Run Code Online (Sandbox Code Playgroud)

...

我明白了

2 1 10    <-- 2 enquiries for product code 10 in month 1
1 1 11    <-- 1 enquiries for product code 11 in month 1
2 2 10    <-- 2 enquiries for product code 10 in month 2
etc
Run Code Online (Sandbox Code Playgroud)

作为一个额外的问题,是否有一种简单的方法来命名每个月,所以输出是1月,2月,3月,而不是月份列中的1,2,3?

bas*_*shu 6

试试这个

Select count(id) As Customers, DatePart(month, enquiryDate) as MonthTotal, productCode From customerEnquiries
where enquiryDate > '2012-01-01 00:00:00'
group by productCode, DatePart(month, enquiryDate)
Run Code Online (Sandbox Code Playgroud)

这可能对你有所帮助.