有没有办法做到这一点?我想检索字段中的每个数据计数
这是我的代码..
Dim cmd1 As New SqlCommand("SELECT COUNT(support) AS support " & _
"FROM Studz_Table WHERE support ='others'",conn)
dim int1 as integer = cmd1.executescalar
Dim cmd2 As New SqlCommand("SELECT COUNT(support) AS support " & _
"FROM Studz_Table WHERE support ='myself'",conn)
dim int2 as integer = cmd1.executescalar
Dim cmd3 As New SqlCommand("SELECT COUNT(support) AS support " & _
"FROM Studz_Table WHERE support ='parent'",conn)
dim int3 as integer = cmd1.executescalar
有没有简单的方法可以做到这一点?
答案 0 :(得分:1)
您可以使用SUM和CASE的组合来检索每种类型的计数。
Dim cmd As New SqlCommand("SELECT SUM(CASE WHEN support = 'others' THEN 1 ELSE 0 END) AS OthersCount, " & _
"SUM(CASE WHEN support = 'myself' THEN 1 ELSE 0 END) AS MyselfCount, " & _
"SUM(CASE WHEN support = 'parent' THEN 1 ELSE 0 END) AS ParentCount " & _
"FROM Studz_Table WHERE support ='others'",conn)
您需要使用ExecuteReader
代替ExecuteScalar
来访问每列:
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int int1 = reader[0];
int int2 = reader[1];
int int3 = reader[2];
}