如何计算特定子字符串在数据库中出现的次数

时间:2013-10-16 05:51:30

标签: asp.net ms-access-2007

我的Access数据库数据如下所示:

srno       likes
user 1     001,002,003
user 2     001,004,005,007
user 2     001,007,009,001
etc

我想计算likes列中每个单独值的次数,即001002等,显示在表格中。

我使用了这段代码:

 cnn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("App_Data\Acetech.mdb"))
        cnn.Open()
        msg = "SELECT COUNT(001) FROM (productfeedback) WHERE three like '001' OR second like '001' "

        cmd = New OleDbCommand(msg, cnn)
        str = cmd.ExecuteScalar()

        cnn.Close()

应显示001 4

    If str Is DBNull.Value Then
        Label12.Text = "0"
    Else
        Label12.Text = Format(CStr(TextBox2.Text)) & Convert.ToInt32(str)
    End If

1 个答案:

答案 0 :(得分:0)

也许你可以在代码而不是sql中解决它。我试过VB.NET,但这不是我的第一语言,我使用了测试数据表

Dim dt As New DataTable()

dt.Columns.Add("srno", GetType(String))
dt.Columns.Add("likes", GetType(String))

dt.Rows.Add("User 1", "001,002,003")
dt.Rows.Add("User 2", "001,004,005,007")
dt.Rows.Add("User 3", "001,007,009,001")

Dim q = From l In dt.AsEnumerable() _
            Select l

Dim likes As New List(Of String)()
For Each row In q
    likes.AddRange(row("likes").Split(","))
Next

Dim likesGroupedBy = likes.GroupBy(Function(item) item).[Select](Function(group) New With { _
 group.Key, _
 Key .Count = group.Count() _
})

Dim ret As String = String.Empty
For Each row In likesGroupedBy
    ret += String.Format("key:{0}, count:{1}" + Environment.NewLine, row.Key, row.Count)
Next