制定代码和SQL查询

时间:2015-03-30 14:47:15

标签: sql-server visual-studio datatable

我在DB中有一个名为'Retail'的表

CustomerID       Itemset
    1               1
    1               3
    1               7 
    2               6
    2               7
    3               4
    ...            ...

我想在数据表'矩阵'中写这个表,其中行是Itemset = {1,2,3,4,5,6 ....,k},列是CustomerID = {1,2,3 ,4,...,X} 如果'Itemset'属于CustomerID,则行为1。

我想要的输出就像..

   1  2  3  4  5  6  7 ............. x
 1 1  0  1  0  0  0  1 0 0 0 0 0 0 0 0
 2 0  0  0  0  0  1  1 0 0 0 0 0 0 0 0 
 3 0  0  0  1  0  0  0 0 0 0 0 0 0 0 0
 4
 5
 6         /And so on!
 7
 8
 9

` 我试图对它进行编码,但问题出在VS参数中,用于SQL查询不能与循环一起使用。

这是我的代码 -

 objConnection.Open()
Dim matrix As DataTable = New DataTable("Retail")
 intcount = 0
    For intcount = 1 To noofCustomerID_col
        matrix.Columns.Add(intcount, GetType(Integer))
    Next
    Dim i As Integer

    Dim workRow As DataRow
    Dim Boolin As Boolean    
For i = 1 To 9
        ObjCommand.CommandText = "Select count(*) from Retail Where CustomerID=@in and Itemset=@in"
        ObjCommand.Parameters.AddWithValue("@in", i) {{I Get Error here as I can't Loop Parameters}}
        Boolin = ObjCommand.ExecuteScalar()

        workRow = matrix.NewRow()
        workRow(0) = i
        workRow(1) = Boolin
        matrix.Rows.Add(workRow)
    Next

请帮助。我知道这段代码完全错了,如果你能提出完全不同的做法,那也没关系。我已经被困了一段时间了!谢谢。 如果需要澄清,我将在评论中多次解释。

1 个答案:

答案 0 :(得分:0)

像Tab Alleman建议的那样,SQL PIVOT可以派上用场。 还需要动态SQL。

DECLARE @DynamicColumn  NVARCHAR(MAX),
        @DynamicQuery   NVARCHAR(MAX)


SELECT @DynamicColumn = SELECT '[' + CONVERT(NVARCHAR, CustomerID) + '],'
                        FROM Retail AS Customer
                        ORDER BY CustomerID
                        FOR XML PATH('')

SELECT @DynamicColumn = SUBSTRING(@DynamicColumn, 0, DATALENGTH(@DynamicColumn) / 2)--REMOVE EXTRA ","


SELECT @DynamicQuery = 'SELECT *
                        FROM (  SELECT  CustomerID,
                                        ItemSet
                                FROM Retail) AS D
                        PIVOT
                        (
                            COUNT([CustomerID])
                            FOR Itemset IN (' +  @DynamicQuery  + ')
                        ) AS P'

EXECUTE(@DynamicQuery)