I have a database with two tables. Advertisements and Records as it’s foreign key. I need to count how often a record of an advertisement occurs and order by ascending.
I am assuming that I have to use a combination of a join and a group by clause to accomplish this. It just isn’t working the way I would like. Below is the code I have so far.
Public Shared Function SortAdsByHitCount() As DataTable
Dim dt As New DataTable
Try
Using context As New QREntities()
Dim ads = (From advertisement In context.QRAdvertisements
Join record In context.QRRecords On advertisement.adId Equals record.adId
Select advertisement.adId, advertisement.adRedirectUrl, advertisement.adType, advertisement.adData, count = record
Order By AdData Ascending).ToList()
'Dim ads = (From advertisement In context.QRAdvertisements
' Group advertisement.adId By advertisement.adId Into Group _
' Order By Group.Count() Ascending _
' Select Advertisement.AdRedirectUrl, Advertisement.AdType, Advertisement.AdData, Count = Group.Count()).ToList()
'Set the column headers and their accepted data types
dt.Columns.Add("adId", GetType(Integer))
dt.Columns.Add("adRedirectUrl", GetType(String))
dt.Columns.Add("adType", GetType(String))
dt.Columns.Add("adData", GetType(String))
dt.Columns.Add("hitCount", GetType(Integer))
For Each a In ads
dt.Rows.Add(a.adId, a.adRedirectUrl, a.adType, a.adData, a.Count)
Next
End Using
Catch ex As Exception
Return Nothing
End Try
Return dt
End Function
I basically need 4 rows from one table and I just include the count of the occurrence from the other. The advertisement datarow must know how many times it has been represented in the records table. So essentially, the gridview/listview would show the user a list of ads sorted by the frequency that that ad has been used.
Ex:
Advertisements
Ad id Ad Type Ad Date Ad Occurrence
1 Automotive 13/12/2012 10
2 Personal 10/12/2012 5
3 Retail 02/11/2012 3
Here you need to be using a grouping function so you have access to the
.Count()extension of the group. To do this in static syntax would look like this: