将行传输到列

时间:2015-10-09 19:36:49

标签: sql sql-server

我在xml中有这样的东西

c1.1    test
c1.2    10
c1.3    100
c2.1    test1
c2.2    10
c2.3    1000

我希望转变成这样的

test    10  100
test1   10  1000

请帮助。我尝试使用枢轴并且无法破解它。需要提到的是c1.1,c1.2,c1.3是一个系列,这3个必须在我的行中

3 个答案:

答案 0 :(得分:0)

Pivot会完全按照您的意愿行事,如下所示:

select * from (
  select left(type,2) as row, right(type, 1) as col, value 
  from Table1
) S pivot (
  max(value) for col in ([1], [2], [3])
) P

SQL Fiddle

中的示例

答案 1 :(得分:0)

SQL Fiddle

MS SQL Server 2014架构设置

CREATE TABLE Table1
    ([Code] varchar(20), [Value] varchar(20))
;

INSERT INTO Table1
    ([Code], [Value])
VALUES
    ('c1.1', 'test'),
    ('c1.2', '10'),
    ('c1.3', '100'),
    ('c2.1', 'test1'),
    ('c2.2', '10'),
    ('c2.3', '1000')
;

查询1

select
      Value1, Value2, Value3
from (
      select
             Value as Value1
           , lead(Value,1) over(partition by left(t1.code,charindex('.',t1.code)-1)
                                order by substring(t1.code,charindex('.',t1.code)+1,len(t1.code))) as Value2
           , lead(Value,2) over(partition by left(t1.code,charindex('.',t1.code)-1)
                                order by substring(t1.code,charindex('.',t1.code)+1,len(t1.code))) as Value3

      from table1 t1
     ) as derived
where Value3 is not null

<强> Results

| Value1 | Value2 | Value3 |
|--------|--------|--------|
|   test |     10 |    100 |
|  test1 |     10 |   1000 |

答案 2 :(得分:0)

在SqlServer 2008架构设置中,我们可以使用Row_number。基于我给出此代码的示例数据。

DECLARE @Table1 TABLE 
    (val varchar(4), col varchar(5))
;

INSERT INTO @Table1
    (val, col)
VALUES
    ('c1.1', 'test'),
    ('c1.2', '10'),
    ('c1.3', '100'),
    ('c2.1', 'test1'),
    ('c2.2', '10'),
    ('c2.3', '1000')
;
Select [1] as [Value1],[2] as [Value2],[3] as [Value3]from (
select SUBSTRING(reverse(val),0,CHARINDEX('.',Reverse(val))) R,
col
,ROW_Number()OVER(PARTITION BY SUBSTRING(reverse(val),0,CHARINDEX('.',reverse(val))) Order by val) RN
 from @Table1)T
PIVOT(max(col) for R IN ([1],[2],[3]))PVT