如何从数据库插入Matrix

时间:2015-03-28 08:26:27

标签: sql sql-server vb.net matrix

我想从数据库(零售)创建一个矩阵

的矩阵
CustomerID    Itemset
    1            1
    1            2
    1            4
    2            1
    2            5
    3            2
    3            4
    4            1
    5            2

这是我想要的输出VB-CustomerID是列,而Itemset是Rows。如果物品集由客户“0”

购买,则为“1”
      1   2   3   4   5  (CustomerID)
  1   1   1   0   1   0
  2   1   0   0   0   1
  3   0   1   0   1   0
  4   1   0   0   0   0
  5   0   1   0   0   0

这是我构建的代码,但并不多。如何循环SQL查询?或者这完全是错误的代码?

  Dim noofitems_row As Integer
    Dim noofCustomerID_col As Integer

    objConnection.Open()

    ObjCommand.CommandText = "select Max(Itemset) from Retail "
    noofitems_row = ObjCommand.ExecuteScalar()

    ObjCommand.CommandText = " select Max(customerID) from Retail"
    noofCustomerID_col = ObjCommand.ExecuteScalar()

    objConnection.Close()
    Dim matrix As Integer(,)
    matrix = New Integer(noofitems_row - 1, noofCustomerID_col - 1) {}


    For i = 0 To noofitems_row - 1
        For j = 0 To noofCustomerID_col - 1
            matrix(i, j) = >WHAT DO I CODE HERE?
        Next
    Next
End Sub

先谢谢你。如果对该问题有任何疑问,我将多次回复。

1 个答案:

答案 0 :(得分:0)

  

我的答案在c#中,但是将其用作算法。

首先,您需要通过以下方式读取数据:

string query = "SELECT * FROM TableName";
string conString = objConnection.ConnectionString;
DataTable dt = new DataTable();
new SqlDataAdapter(query, conString).Fill(dt);

现在您的数据位于DataTabl dt

当您声明int数组时,其默认值为0,而您只需查找并更新某些地点1

for (int i = 0; i < dt.Rows.Count; i++)
{
    int itemSet = Int32.Parse(dt.Rows[i]["Itemset"].ToString());
    int customerID = Int32.Parse(dt.Rows[i]["CustomerID"].ToString());
    /*Update [itemSet,customerID] and [customerID,itemSet] of array*/
}