sqlserver按月分組統計資料,.net月份為空的補0——優化版
阿新 • • 發佈:2021-01-13
現在資料庫中存在大量資料,我這裡想要按月份分組統計資料中的數量
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 householdauditdata(int id, out int result) { try { string sql =
[email protected]" 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); DataTable dtNew = new DataTable(); if (dt != null && dt.Rows.Count > 0) { dtNew = new DataTable(); dtNew.Columns.Add("name", typeof(System.String)); dtNew.Columns.Add("value", typeof(System.Int32)); for (int i = -29; i <= 0; i++) { DataRow row = dtNew.NewRow(); var date = dt.AsEnumerable().Where(n => n.Field<string>("name") == DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")).FirstOrDefault(); if (date != null) { row["name"] = date.Field<string>("name"); row["value"] = date.Field<int>("value"); } else { row["name"] = DateTime.Now.AddDays(i).ToShortDateString(); row["value"] = 0; } dtNew.Rows.Add(row); } } else { dtNew = new DataTable(); dtNew.Columns.Add("name", typeof(System.String)); dtNew.Columns.Add("value", typeof(System.Int32)); for (int i = -29; i <= 0; i++) { DataRow row = dtNew.NewRow(); row["name"] = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"); row["value"] = 0; dtNew.Rows.Add(row); } } result = 0; return dtNew; } } catch (Exception ex) { result = 1; 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 } ] }