其中count sql语句

时间:2012-07-28 14:01:30

标签: sql vb.net

我已将count(ProductQuantity)存储到列表中。由于每个ProductID都有不同的计数(ProductQuantity),我试图根据计数(ProductQuanity)检索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语句是什么

3 个答案:

答案 0 :(得分:0)

因此,您需要具有给定数量的记录,然后只需删除COUNT

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

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

答案 1 :(得分: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);
...

答案 2 :(得分: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 = @DesquireQuantity的产品,并为@DesiredQuantity分配变量i的值。参数可以防止SQL注入,以及其他潜在的问题。