将行转置为没有聚合的列(枢轴)

时间:2018-10-23 04:01:48

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

我在SQL Server中具有下表:

CREATE TABLE yourtable
( 
      [ID] int,
      [FORMID] int,
      [NAME] VARCHAR(30), 
      [VALUE] VARCHAR(30), 
      [CREATED] datetime,
);

INSERT INTO yourtable ([ID], [FormID], [NAME], [VALUE], [CREATED])
VALUES
    (1, 1, 'First N', 'A b', '2018-01-01'),
    (2, 1, 'Last N', 'c d', '2018-01-01'),
    (3, 1, 'Email', 'a@GM', '2018-01-01'),
    (4, 2, 'First N', 'a b2', '2018-01-01'),
    (5, 2, 'Last N', 'c d2', '2018-01-01'),
    (6, 2, 'Email', 'c@GM2', '2018-01-01');

我需要输出类似这样的内容,如果需要添加其他列,请不要介意。

First N | Last N
--------+--------
A b     | c d
a b2    | c d2

非常感谢,

2 个答案:

答案 0 :(得分:0)

将您的表格分成两个表格,如下所示,并基于自动增量列,您可以将它们结合起来以获得名字和姓氏的组合。 当然,我假设您的表格数据中有 LOT 件事:)

declare @yourtable table
    ([NAME] varchar(30), [VALUE] varchar(30))
;

INSERT INTO @yourtable
    ([NAME], [VALUE])
VALUES
    ('First N', 'A b'),
    ('Last N', 'c d'),
    ('Email', 'a@GM'),
    ('First N', 'a b2'),
    ('Last N', 'c d2'),
    ('Email', 'c@GM2')

    declare @firstName table(id int identity(1,1),[First N] varchar(100))
    declare @lastName table(id int identity(1,1),[Last N] varchar(100))

    Insert Into @firstName([First N])
    select value 
    from @yourtable where name= 'First N'

    Insert Into @lastName([Last N])
    select value 
    from @yourtable where name= 'Last N'

    SELECT [First N],[Last N] FROM  @firstName f LEFT JOIN  @lastName l on f.id = l.id

答案 1 :(得分:0)

不是最好的方法,但是为了方便起见,我使用了子查询

Select
   formid as fid,
   (Select value from yourtable where Name = 'First Name' and formid=fid) as FirstName,
   (Select value from yourtable where Name = 'Last Name' and formid=fid) as LastName
From yourtable