DataTable dt = new DataTable(); //原來的資料
dt = Get(); //取得資料,PS. Get()是我自己寫的Function,要記得換成你取得DataTable的function
//將原來的DataTable做Distinct並複製到新DataTable,ToTable的第一個參數是設定是否
//要做Distinct,當然要設成true,其他參數是要做Group By的欄位名稱
DataTable dtGroup = dt.DefaultView.ToTable(true, "column1", "column2");
//開始加欄位
dtGroup.Columns.Add("CountColumn");
dtGroup.Columns.Add("SumColumn");
dtGroup.Columns.Add("AvgColumn");
int count = 0;
for (int i = 0; i < dtGroup.Rows.Count;i++) {
//取資料,用String是因為上方加欄位時,沒指定型別為數字
string strCount = dt.Select("column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").Length.ToString();
string strSum = dt.Compute("SUM(column3)", "column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").ToString();
string strAvg = dt.Compute("AVG(column4)", "column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").ToString();
//設定資料
dtGroup.Rows[i]["CountColumn"] = (strCount == "" ? "0" : strCount);
dtGroup.Rows[i]["SumColumn"] = (strSum == "" ? "0" : strSum);
dtGroup.Rows[i]["AvgColumn"] = (strAvg == "" ? "0" : strAvg );
}
dt = Get(); //取得資料,PS. Get()是我自己寫的Function,要記得換成你取得DataTable的function
//將原來的DataTable做Distinct並複製到新DataTable,ToTable的第一個參數是設定是否
//要做Distinct,當然要設成true,其他參數是要做Group By的欄位名稱
DataTable dtGroup = dt.DefaultView.ToTable(true, "column1", "column2");
//開始加欄位
dtGroup.Columns.Add("CountColumn");
dtGroup.Columns.Add("SumColumn");
dtGroup.Columns.Add("AvgColumn");
int count = 0;
for (int i = 0; i < dtGroup.Rows.Count;i++) {
//取資料,用String是因為上方加欄位時,沒指定型別為數字
string strCount = dt.Select("column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").Length.ToString();
string strSum = dt.Compute("SUM(column3)", "column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").ToString();
string strAvg = dt.Compute("AVG(column4)", "column1='" + dtGroup.Rows[i]["column1"].ToString() + "'").ToString();
//設定資料
dtGroup.Rows[i]["CountColumn"] = (strCount == "" ? "0" : strCount);
dtGroup.Rows[i]["SumColumn"] = (strSum == "" ? "0" : strSum);
dtGroup.Rows[i]["AvgColumn"] = (strAvg == "" ? "0" : strAvg );
}
最後dtGroup就是Group By後的資料了。
網誌管理員已經移除這則留言。
回覆刪除