0

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() は count(ProductQuanity) を格納するメソッドです

count(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 に答える