问题描述
我想计算表格中每本书的作者数量。 我得到的结果不正确。
表格标题_作者测试:
ISBN Au_ID2 书 1 - 作者 1, 书 2 - 作者 2, 书 2 - 作者 3,
结果 - 运行代码后:
2 本书,1 个作者, 2 位作者的 0 本书, 3 位作者的 0 本书, ...
结果应该是:
1 本书,1 个作者, 1 本书,2 位作者, 3 位作者的 0 本书, ...
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load
Dim BooksConnection As OleDbConnection
Dim ISBNCommand As OleDbCommand
Dim ISBNAdapter As OleDbDataAdapter
Dim ISBNTable As DataTable
'connect to books database
BooksConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BooksDB.mdb;")
BooksConnection.open()
'establish Command object
ISBNCommand = New OleDbCommand("Select * from Title_AuthorTest ORDER BY ISBN",BooksConnection)
'establish data adapter / data table
ISBNAdapter = New OleDbDataAdapter()
ISBNAdapter.SelectCommand = ISBNCommand
ISBNTable = New DataTable()
ISBNAdapter.Fill(ISBNTable)
'count authors
Dim Author As Integer
Dim AuthorCount(10) As Integer 'make array
Dim LastISBN As String
LastISBN = ""
'allow up to 10 authors per title
For Author = 1 To 10
AuthorCount(Author) = 0 'set authorcount for all the authors to zero
Next Author
'set to the first author
Author = 1
'check each row for repeated ISBN
Dim MyRow As DaTarow
'LastISBN = ISBNTable.Rows(0)("ISBN").ToString 'get first ISBN
For Each MyRow In ISBNTable.Rows 'loop the table
If MyRow.Item("ISBN").Equals(LastISBN) Then
'is ISBN repeated then add Author
Author += 1
Else
'no more authors for this ISBN
AuthorCount(Author) += 1
Author = 1
LastISBN = MyRow.Item("ISBN").ToString 'zet LastISBN op ISBN die je net hebt geconsulteerd
End If
Next
'display results number of books with x authors
For Author = 1 To 10
ListBox1.Items.Add(Str(AuthorCount(Author)) + " Books with" + Str(Author) + " Authors")
Next
'dispose
BooksConnection.Close()
BooksConnection.dispose()
ISBNCommand.dispose()
ISBNAdapter.dispose()
ISBNTable.dispose()
End Sub
End Class
解决方法
我将开始更改 SQL 命令并使用 GROUP BY
Dim cmdText = "SELECT ISBN,COUNT(ISBN) as NrAuthors from Title_AuthorTest
GROUP BY ISBN
ORDER BY COUNT(ISBN) DESC"
ISBNCommand = New OleDbCommand(cmdText,BooksConnection)
现在您已将所有图书按 ISBN 分组,并且每条记录都包含 ISBN 和该 ISBN 的作者人数。
在这一点上,您的代码可以通过
For Each MyRow as DataRow In ISBNTable.Rows
Dim numAuthors As Integer = Convert.ToInt32(MyRow("NrAuthors"))
AuthorCount(numAuthors) += 1
Next
当然,这将允许最多 10 位作者撰写一本书。如果有一本书的作者超过 10 位,我们需要在索引 AuthorCount 数组之前检查或使用不同的结构更改我们存储此信息的方式