1. 查詢平均值語法
select avg(要計算的值) as 別名 from 表名 select 別名=avg(要計算的值) from 表名
2.獲取資料總條數
select count(*) as 別名 from 表名 select 別名=count(*) from 表名
以下是舉例:
public Dictionary<string, string> keyValuePairs() { // as 後面是取的別名 //count(*) 查詢所有結果 //avg 計算平均數 //CSharp 表中的欄位 //SQLServerDB表中的欄位 string sql = "select count(*) as total,avg(CSharp) as avgCSharp,avg(SQLServerDB) as avgSQLServerDB from ScoreList;"; //select count(*) as qCount from Students where StudentId not in (select StudentId from ScoreList)的意思是 //根據StudentId排除已經在ScoreList表中存在的StudentId,返回沒有存在的 sql += "select count(*) as qCount from Students where StudentId not in (select StudentId from ScoreList)"; //這句是封裝的從資料庫查詢 SqlDataReader sqlData = SqlHelper.GetReader(sql); //定義一個鍵值對集合 Dictionary<string, string> keyValues = new Dictionary<string, string>(); while (sqlData.Read()) { keyValues.Add("total", sqlData["total"].ToString()); keyValues.Add("avgCSharp", sqlData["avgCSharp"].ToString()); keyValues.Add("avgSQLServerDB", sqlData["avgSQLServerDB"].ToString()); } //跳轉到另外一個結果集,因為上面是兩個查詢語句 if (sqlData.NextResult()) { while (sqlData.Read()) { keyValues.Add("qCount", sqlData["qCount"].ToString()); } } return keyValues; }