0

我已将 count(ProductQuantity) 存储到列表中。由于每个 ProductID 都有不同的计数(ProductQuantity),我试图根据计数(ProductQuantity)检索 ProductID。

  For Each i In sumofpquantity()

    Dim sq As String = "SELECT ProductID From OrderDetail Where COUNT(ProductQuantity)= " & i & ""
        Dim cmd2 As SqlCommand = New SqlCommand(sq, connection12)
        Dim reading As SqlDataReader = cmd2.ExecuteReader()
        While reading.Read()

            list.Add(reading.GetInt32(reading.GetOrdinal("ProductID")))

        End While
        reading.Close()
    Next i

sumofpquantity() 是存储计数的方法(ProductQuanity)

根据计数(ProductQuantity)检索productid的正确sql语句是什么

4

3 回答 3

0

所以你想要给定数量的记录,然后简单地删除COUNT

Dim sq = "SELECT ProductID From OrderDetail Where ProductQuantity = " & i 

COUNT是一个聚合函数。所以你需要一个GROUP BY ProductID例子。您不能计算已经是单个数值的东西。

于 2012-07-28T14:03:38.057 回答
0

您可以使用having子句搜索具有特定出现次数的产品。例如,这将查找具有 42 个销售额的产品:

select  ProductID 
from    OrderDetail 
group by
        ProductID 
having  SUM(ProductQuantity) = 42

要将数字 42 传递给数据库,请考虑使用参数:

Dim sq As String = _
    "select  ProductID" & _
    "from    OrderDetail" & _
    "group by" & _
    "        ProductID" & _
    "having  SUM(ProductQuantity) = @cnt"
Dim cmd2 As SqlCommand = New SqlCommand(sq, connection12)
cmd2.Parameters.AddWithValue("@cnt", 42);
...
于 2012-07-28T14:07:23.287 回答
0

好吧,使用参数化查询是一个好习惯,如下所示:

Dim sq as String = "SELECT ProductID " & _
                   "FROM OrderDetail " & _
                   "WHERE ProductQuantity = @DesiredQuantity"
Dim cmd2 as SqlCommand = New SqlCommand(sq, connection12)
cmd2.Parameters.AddWithValue("@DesiredQuantity", i)

通过此查询,SQL 查找 ProductQuantity = @DesiredQuantity 的产品,并为 @DesiredQuantity 分配变量 i 的值。参数可防止 SQL 注入以及其他潜在问题。

于 2012-07-28T14:07:26.597 回答