现在数据库中存在大量数据,我这里想要按月份分组统计数据中的数量
select
convert(varchar(7),Datetimes,120) as times,
count(Id) as Counts
from 表名
group by convert(varchar(7),Datetimes,120)
这里的Datetimes是数据表中的时间字段名称,Id是主键字段名称,最后分组也是按照月份分组,我这里进行的月份的转换
结果为:
但是有个问题,我想查询前6个月的所有月份统计,但是有的月份为空,这里我就要在.net后台进行补0
public DataTable GetMouthCount()
{
try
{
string sql = $@" select
convert(varchar(7),Datetimes,120) as times,
count(Id) as Counts
from 表名
group by convert(varchar(7),Datetimes,120)";//字符串
using (var conn = new SqlConnection(connStr))
{
DataTable dt = conn.GetDataTable(sql);
string now = (DateTime.Now.ToString()).Substring(0, 9);//截取计算机当前日期
now = now.Replace('/', '-');//替换字符串
string A = now.Substring(now.Length - 2, 1);/