2012-01-31 34 views
0

我有这个数据库表就叫人如何统计数据库中的记录?

People 
peopleID peopleName relationship customerID 
1   A   aunty   1 
2   B   aunty   1 
3   C   second uncle 1 
4   D   aunty   2 

我要去怎么算,其中客户ID = 1,如果关系是一样的,它被算作1

所以从人数上面的数据库表,我应该得到3的结果,并将3的结果放在GridView中Label1中?

我能得到的计数值为只在客户ID = 1,但我想不出我该怎么怎么当我正确地理解你的问题,如果关系部分

Protected Sub GridView2_RowDataBound(sender As Object, e As 
System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound 
     If e.Row.RowType = DataControlRowType.DataRow Then 
      'Do your processing here... 

      Dim txt As TextBox = DirectCast(e.Row.FindControl("Label1"), TextBox) 
      Dim adapter As New SqlDataAdapter 
      Dim ds As New DataSet 
      'Dim sql As String 

      Dim connectionString = ConfigurationManager.ConnectionStrings("ProjData").ConnectionString 
      Dim myConn As New SqlConnection(connectionString) 

      Dim cmd = "Select * From People Where customerID='" & Session("customerID") & "' " 

      ' Dim myCmd As New SqlCommand(cmd, myConn) 

      Try 
       myConn.Open() 
       Dim myCmd As New SqlCommand(cmd, myConn) 
       adapter.SelectCommand = myCmd 
       adapter.Fill(ds, "People") 
       adapter.Dispose() 
       myCmd.Dispose() 
       txt.Text = ds.Tables(0).Rows.Count 



      Catch ex As Exception 
       MsgBox("Can not open connection ! ") 
      End Try 
     End If 
    End Sub 

回答

0

计数,以下SQL语句应该在您需要时给予您计数。

Select count(peopleID) 
From People 
Where customerID = 1 
Group by relationship, customerID 

如果此答案无法解决您的问题,请在您的问题的添加进一步的信息。

0

在您的代码中,您获取所有行并对其进行计数。您也可以执行一个查询来计算服务器上的行数。这会表现得更好!

string sql = "SELECT COUNT(*) FROM People Where customerID='" & Session("customerID") & "' " 
... 
int rowCount = myCmd.ExecuteScalar(); 

如果要计算具有相同关系的行数,则必须使用group by。

你有你的SQL更改为:

string sql = 'SELECT COUNT(peopleId) FROM People Where customerID='" & Session("customerID") & "' "GROUP BY relationship, customerId" 
+0

你为什么按关系分组? – 2012-11-02 15:11:31

1

你应该换你的SqlConnection在using语句(不知道你怎么做,在VB)。在你的例子中,你不关闭连接,using语句自动为你做这件事(另一种方法是在finally块中关闭连接)