我有一个名为people
的数据库表 People
peopleID peopleName relationship customerID
1 A aunty 1
2 B aunty 1
3 C second uncle 1
4 D aunty 2
我如何计算customerID = 1的人数,如果关系相同,则计为1
所以从上面的数据库表中,我应该得到3的结果并将3的结果放在gridview中的Label1中?
我可以获得customerID = 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 :(得分:1)
您应该将SqlConnection包装在using语句中(不确定如何在VB中执行此操作)。在您的示例中,您不会关闭连接,using语句会自动为您执行此操作(替代方法是在finally块中关闭连接)
答案 1 :(得分:0)
当我正确理解您的问题时,以下SQL语句应该根据您的需要为您提供计数。
Select count(peopleID)
From People
Where customerID = 1
Group by relationship, customerID
如果此答案无法解决您的问题,请在您的问题中添加更多信息。
答案 2 :(得分:0)
在您的代码中,您获取所有行,然后计算它们。您还可以执行将计算服务器上的行数的查询。这会表现得更好!
string sql = "SELECT COUNT(*) FROM People Where customerID='" & Session("customerID") & "' "
...
int rowCount = myCmd.ExecuteScalar();
如果要计算具有相同关系的行数,则必须使用分组。
您必须将sql更改为:
string sql = 'SELECT COUNT(peopleId) FROM People Where customerID='" & Session("customerID") & "' "GROUP BY relationship, customerId"