0

我有一个包含两个表的数据库。广告和记录作为它的外键。我需要计算广告记录出现的频率并按升序排列。

我假设我必须结合使用 join 和 group by 子句来完成此操作。它只是没有按照我想要的方式工作。以下是我到目前为止的代码。

    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

我基本上需要一张表中的 4 行,而我只包括另一张表中出现的次数。广告数据行必须知道它在记录表中出现了多少次。因此,从本质上讲,gridview/listview 将向用户显示按广告使用频率排序的广告列表。

例如:广告

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
4

1 回答 1

1

在这里,您需要使用分组功能,以便您可以访问.Count()组的扩展。在静态语法中执行此操作如下所示:

Dim ads = (From advertisement In context.QRAdvertisements
                      Group Join record In context.QRRecords 
                      On advertisement.adId Equals record.adId 
                      Into records = Group
                      Select advertisement.adId, advertisement.adRedirectUrl, advertisement.adType, advertisement.adData, count = records.Count()
                      Order By AdData Ascending).ToList()
于 2012-12-13T09:58:33.757 回答