如何计算数据库中的常用字段?

时间:2013-03-08 12:29:06

标签: c# asp.net sql-server-2008

Id    Name     City
1     Hits     Baroda
2     Ajay     Chennai
3     Hitesh   Baroda

如何计算城市以及如何在变量中存储计数值?

3 个答案:

答案 0 :(得分:3)

如果您只想在城市中计算总数,请尝试查询

SELECT COUNT(*) as TotalCityCount From TableName

如果您只需要城市中的总计数,请删除重复的城市

SELECT COUNT(distinct City) as TotalCityCount  From   Your TableName 

并尝试使用以下c#代码:

public DataView GetCityCount()
{
   using (SqlConnection con = new SqlConnection("Put Your Connection String"))// **must Put Your Connection String**
   {
      string sql1 = string.Format(@"SELECT COUNT(*) as TotalCityCount From TableName");
      SqlDataAdapter da1 = new SqlDataAdapter(sql1, con);
      DataSet ds1 = new DataSet();
      con.Open();
      da1.Fill(ds1);
      return ds1.Tables[0].DefaultView;
   }
} 

Public Void getTotal()
{
   DataView dv=GetCityCount();
   int totalcity=Convert.ToInt32(dv.Tables[0]["TotalCityCount"])//You get the total Count value in this totalcity variable
}

答案 1 :(得分:2)

这将为您计算每个城市的人数,在这里您可以获得城市数量

SELECT 
      City, 
      COUNT(Id) as total 
 From 
      TableName 
 Group by 
       City

结果将是

Baroda    2
Chennai   1

或者,如果您只想要城市总数,那么就像这样写

SELECT 
     COUNT(distinct City) as total 
From 
     TableName 

答案 2 :(得分:0)

可能就像你需要的那样

declare @Count int  --(or bigint)
Select @Count=count(city)
from Citytable
return @Count (or print @Count or Select @Count)