【问题标题】:How to convert column to row?如何将列转换为行?
【发布时间】:2011-12-21 04:17:04
【问题描述】:

我需要你的帮助.. 我有一个动态查询,它以这种格式返回数据..

Item1  Item1Remarks  Item2  Item2Remarks  Item3  Item3Remarks  Item4  tem4Remarks
==
2      bla bla       5      bla bla       1      bla bla       4      bla bla

项目名称可以变化(可以更改,因为数据是动态的)。项目列包含项目数量。

现在我需要这种格式的数据。

Item    Qty Remarks
==
Item1   2   bla bla
Item2   5   bla bla
Item3   1   bla bla
Item4   4   bla bla

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

请参阅 MSDN 上的 Using PIVOT and UNPIVOT

【讨论】:

    【解决方案2】:

    要具体回答您的问题,您基本上需要一个复杂的多列 UNPIVOT 查询,例如:

    SELECT Item, Qty, Remarks
    FROM ItemDetail
    UNPIVOT -- This UNPIVOT gives us the Item column
    (  
      Qty FOR Item IN (Item1, Item2, Item3, Item4)  
    ) TheItem  
    UNPIVOT -- This UNPIVOT gives us the corresponding Remarks column
    (  
      Remarks FOR ItemRemarks IN (Item1Remarks, Item2Remarks, 
                                  Item3Remarks, Item4Remarks)  
    ) Ct  
    WHERE RIGHT(Item,1)=SUBSTRING(ItemRemarks,5,1) -- Match items with their remarks
    

    您没有指定表的名称,因此请将 ItemDetail 替换为其实际名称。

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 1970-01-01
      • 2014-08-30
      • 2016-10-25
      相关资源
      最近更新 更多