现在数据库中存在大量数据,我这里想要按月份分组统计数据中的数量
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);//获取最后一个字符
if (A != "-")//判断当前字符是否为-
{
now = now.Insert(5, "0");
}
//A = now.Substring(now.Length - 1, 1);//获取最后一个字符
//if (A == " ")//判断当前字符是否为-
//{
// now = now.Insert(8, "0");
//}
int Y = Convert.ToInt32(now.Substring(0, 4));
int M = Convert.ToInt32(now.Substring(5, 2));
int D = Convert.ToInt32(now.Substring(8, 2));
int count = dt.Rows.Count;
bool re = false;
//1.创建一个新表
DataTable dr = new DataTable();
//2.给表加个列名:
dr.Columns.Add("times", typeof(System.String));
dr.Columns.Add("Counts", typeof(System.Int32));
//3.给表加行:
DataRow row = dr.NewRow();
for (int i = 0; i < 30; i++)
{
for (int j = count - 1; j >= 0; j--)
{
var year = dt.Rows[j]["times"].ToString();
DateTime Year = Convert.ToDateTime(year);
DateTime Now = Convert.ToDateTime(now);
if (Year == Now)
{
var Count = dt.Rows[j]["Counts"].ToString();
//4.给列赋值
row = dr.NewRow();
row["times"] = now;
row["Counts"] = Count;
dr.Rows.Add(row);
re = true;
break;
}
if (j==count-31)
{
break;
}
}
if (re != true)
{
//4.给列赋值
row = dr.NewRow();
row["times"] = now;
row["Counts"] = "0";
dr.Rows.Add(row);
}
else
{
re = false;
}
if (D - 1 == 0)
{
if (M - 1 == 0)
{
Y = Y - 1;
M = 12;
D = 31;/
}
else
{
M = M - 1;
if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12)//大月
{
D = 31;
}
else//小月
{
D = 30; //
}
}
}
else
{
D = D - 1;
}
now = (Y + "-" + M + "-" + D).ToString();
A = now.Substring(now.Length - 2, 1);//获取最后一个字符
if (A != "-")//判断当前字符是否为-
{
now = now.Insert(5, "0");
}
//A = now.Substring(now.Length - 1, 1);//获取最后一个字符
//if (A == "")//判断当前字符是否为-
//{
// now = now.Insert(8, "0");
//}
}
result = 0;
return dr;
}
}
catch (Exception ex)
{
return new DataTable();
}
}
最终的返回数据的格式为:
{
“errcode”: 0,
“errmsg”: “查询成功!”,
“result”: [
{
“times”: “2020-06”,
“Counts”: 6
},
{
“times”: “2020-05”,
“Counts”: 0
},
{
“times”: “2020-04”,
“Counts”: 0
},
{
“times”: “2020-03”,
“Counts”: 0
},
{
“times”: “2020-02”,
“Counts”: 0
},
{
“times”: “2020-01”,
“Counts”: 0
},
{
“times”: “2019-12”,
“Counts”: 0
},
{
“times”: “2019-11”,
“Counts”: 0
},
{
“times”: “2019-10”,
“Counts”: 0
}
]
}