预期或类似的输出

时间:2010-01-25 14:57:17

标签: sql-server-2005

HI,

我的数据如下所示

ItemCode      Attr1    Attr1  InStock
ITEM-000001   43      S      1
ITEM-000001   52      L    2
ITEM-000006   42      R    1
ITEM-000006   44      R    2
ITEM-000009   56      R    1
ITEM-000011   40      R    2

通过使用数据透视表(或任何其他技术)我希望像

一样重新调整

ITEM-000001的输出     43 52     S 1
    L 2 其他人也一样。

亲切的问候,Om

1 个答案:

答案 0 :(得分:1)

嗨我得到了上述视图的解决方案,该视图将用于更改列数据,即Attr1& ATTR2

解决方案如下:

CREATE TABLE #Aggregates
             (
              [On Hand] VARCHAR(50),
              ColumnText VARCHAR(50),
              CellData INT
             )

INSERT INTO #Aggregates
            (
             [On Hand],
             ColumnText,
             CellData
            )
SELECT ISNULL(matrixItem.Attribute2, '--'), matrixItem.Attribute1, item.UnitsInStock
FROM   InventoryMatrixItemView AS matrixItem LEFT OUTER JOIN
       InventoryItemView AS item ON matrixItem.MatrixItemCode = item.ItemCode
WHERE  (matrixItem.Selected = 1 AND matrixItem.ItemCode = @itemCode)

CREATE TABLE #Columns
            (
             ColumnIndex INT IDENTITY (0, 1),
             ColumnText VARCHAR(50)
             )

INSERT INTO     #Columns
                (
                 ColumnText
                )
SELECT DISTINCT ColumnText
FROM           #Aggregates 
ORDER BY       ColumnText

CREATE TABLE #Rows 
             (
              [On Hand] VARCHAR(50)
             )

INSERT INTO    #Rows
                (
                 [On Hand]
                )

SELECT DISTINCT [On Hand]
FROM #Aggregates with(nolock)

DECLARE     @ColumnIndex INT,
            @MaxColumnIndex INT,
            @ColumnText VARCHAR(50),
            @SQL VARCHAR(1000)

SELECT      @ColumnIndex = 0,
            @MaxColumnIndex = MAX(ColumnIndex)
FROM        #Columns


WHILE @ColumnIndex <= @MaxColumnIndex
   BEGIN
      SELECT     @ColumnText = ColumnText
      FROM       #Columns
      WHERE      ColumnIndex = @ColumnIndex

      SELECT     @SQL = 'ALTER TABLE #Rows ADD ' + QUOTENAME(@ColumnText) + ' INT NULL DEFAULT 0'
      EXEC       (@SQL)

      SELECT     @SQL = 'UPDATE #Rows SET ' + QUOTENAME(@ColumnText) + ' = #Aggregates.CellData
                         FROM #Aggregates, #Columns
                         WHERE #Rows.[On Hand] = #Aggregates.[On Hand] 
                         AND #Columns.ColumnText = #Aggregates.ColumnText 
                         AND #Columns.ColumnIndex = ' + CAST(@ColumnIndex AS VARCHAR(12))
      EXEC       (@SQL)

      SELECT  @ColumnIndex = @ColumnIndex + 1 
   END

DROP TABLE #Columns
DROP TABLE #Aggregates

SELECT     #Rows.*
FROM        #Rows
ORDER BY   #Rows.[On Hand]

DROP TABLE  #Rows