Question

Please forgive me for my slow uptake with this problem.

I am trying to compute total votes for each candidate and percentage of those votes.

My logic doesn't seem to be working as I am running into an error that says:

pct not declared

Any ideas how to resolve this?

        For Each row As DataRow In ds.Tables("choices").Rows
        Dim cmdAns As New SqlCommand("select count(*), 100.0 * ((SUM(candidateId)) / (SUM(SUM(candidateId))OVER())) AS pct from ElectionResults where candidateid=@cid", cnn)
        Dim pCid As New SqlParameter("@cid", row("candidateid"))
        cmdAns.Parameters.Add(pCid)
        Dim count As Integer = cmdAns.ExecuteScalar()
        row("CandidateName") = row("CandidateName") & " - " & count & "(" & pct & ") %"
    Next
Was it helpful?

Solution 2

ExecuteScalar()returns only a single value:

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

if you select more than one field you need to use ExecuteReader()

Something like that should work:

For Each row As DataRow In ds.Tables("choices").Rows
    Dim cmdAns As New SqlCommand("select count(*),...candidateid=@cid", cnn)
    Dim pCid As New SqlParameter("@cid", row("candidateid"))
    cmdAns.Parameters.Add(pCid)
    Dim data As SqlDataReader
    data = command.ExecuteReader()
    While data.Read
     If data.HasRows = True Then
        Dim count As String = data(0)
        Dim pct As String = data(1)
        row("CandidateName") = row("CandidateName") & " - " & count & "(" & pct & ") %"
     End If
    End While
Next

OTHER TIPS

You are on the right track, but taking the sum of an id is usually not the right approach.

select count(*),
       (100.0 * (cast(count(*) as float) / SUM(count(*)) over ()) AS pct
from ElectionResults
where candidateid = @cid;

Because SQL Server does integer division, you want to be extra careful that this doesn't happen in the calculation of parentheses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top