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

本文关键字:常用 字段 统计数据库 | 更新日期: 2023-09-27 18:02:51

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

如何计数城市和如何存储它的计数值在一个变量?

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

如果您只想要城市的总数,请尝试查询

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
}

这将给你每个城市的人数,这里你可以得到城市人数

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

结果将是

Baroda    2
Chennai   1

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

SELECT 
     COUNT(distinct City) as total 
From 
     TableName 

可能是你需要的

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