【问题标题】:How to Pivot one Row into One Column如何将一行转为一列
【发布时间】:2014-08-18 13:25:21
【问题描述】:

谁能帮帮我。 我环顾四周,找不到与我需要做的类似的事情。基本上,

我有一个需要旋转的表格,它来自一个平面文件,该文件将所有列加载为一个逗号分隔的列。我需要在枢轴之前将列分解为各自的顺序,并且我有可以很好地做到这一点的程序。但是,此表的关键是我需要先编辑标题才能继续。

我需要帮助将第一列中的信息转换为我创建的另一个表。因此,我需要这个

    ID   Column01

    1    Express,,,Express,,,HyperMakert,,WebStore,Web

就这样结束了……

    New_ID   New_Col

    1        Express
    2        
    3
    4        Express
    5
    6        
    7        HyperMarket
    8
    9        WebStore
    10       Web

请注意,我需要包含原始行中的“黑色”列和。
我查看了下面的链接,但它们没有帮助;

SQL Server : Transpose rows to columns Efficiently convert rows to columns in sql server Mysql query to dynamically convert rows to columns

【问题讨论】:

标签: sql-server sql-server-2012 unpivot


【解决方案1】:

你可以在网上找到很多 SQL Server 中拆分字符串的方法,有些非常复杂,但有些很简单。我喜欢使用动态查询的方式。它很简短(不确定性能,但我相信它不会太糟糕):

declare @s varchar(max)
-- save the Column01 string/text into @s variable
select @s = Column01 from test where ID = 1
-- build the query string
set @s = 'select row_number() over (order by current_timestamp) as New_ID, c as New_Col from (values ('''
          + replace(@s, ',', '''),(''') + ''')) v(c)'

insert newTable exec(@s)    
go
select * from newTable

Sqlfiddle Demo

上面values()子句的使用是某种匿名表,这里是一个简单的例子(这样你可以更好的理解)。以下示例中的 anonymous 表只有 1 列,表名为 v,列名为 c。每行只有一个单元格,应该用一对括号() 包裹起来。这些行以逗号分隔并在values 之后。代码如下:

-- note about the outside (...) wrapping values ....
select * from (values ('a'),('b'),('c'), ('d')) v(c)

结果将是:

   c
------
1  a
2  b
3  c
4  d

只需尝试运行该代码,您就会明白它有多么有用。

【讨论】:

    【解决方案2】:

    您可能想在此处使用计数表。见http://www.sqlservercentral.com/articles/T-SQL/62867/

    declare @parameter varchar(4000)
    
    set @parameter = 'Express,,,Express,,,HyperMakert,,WebStore,Web'
    set @parameter = ',' + @parameter + ',' -- add commas
    
    with
        e1 as(select 1 as N union all select 1), -- 2 rows
        e2 as(select 1 as N from e1 as a, e1 as b), -- 4 rows
        e3 as(select 1 as N from e2 as a, e2 as b), -- 16 rows
        e4 as(select 1 as N from e3 as a, e3 as b), -- 256 rows
        e5 as(select 1 as N from e4 as a, e4 as b), -- 65536 rows
        tally as (select row_number() over(order by N) as N from e5
    )
        select 
            substring(@parameter, N+1, charindex(',', @parameter, N+1) - N-1)
        from tally
        where 
            N < len(@parameter)
            and substring(@parameter, N, 1) = ','
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 2021-09-22
      • 2021-12-18
      • 2013-06-03
      相关资源
      最近更新 更多