SQL。如何从一列中获取值并将其传递给另一列

SQL. How to take value from one column and pass It to another column

我正在使用 SQL-Server 2008。如何从一列中获取值并将其传递给另一列?

正如您在下面的示例数据中看到的那样,有 4 列。我需要获取列名(在本例中为 UserName)并将其传递给 FieldName 列,并将 UserName 列的值传递给 Value 列。

示例数据

GroupId   UserName     FieldName    Value        
1         John Smith   Foo          28
1         John Smith   Bar          2
1         John Smith   FooBar       11
1         John Smith   Bizz         22
2         Peter Jones  Foo          4
2         Peter Jones  Bar          13
2         Peter Jones  FooBar       27
2         Peter Jones  Bizz         23

期望的结果

GroupId   FieldName    Value         
1         Foo          28
1         Bar          2
1         FooBar       11
1         Bizz         22
1         UserName     John Smith
2         Foo          4
2         Bar          13
2         FooBar       27
2         Bizz         23
2         UserName     Peter Jones

我怎样才能实现它?通过使用 PIVOT?但我不确定如何将透视数据合并到现有列。你有什么想法吗?如果有什么不清楚的地方 - 问我,我会尽量提供更多细节。

select GroupId,   FieldName,    Value      
from table 
union 
select distinct GroupId, 'username',  UserName   
from table 

无需 PIVOT ,只需一个简单的 UNION ALL 即可:

SELECT DISTINCT t.groupID,'USERNAME',t.userName
FROM YourTable t
UNION ALL
SELECT s.groupID,s.FieldName,s.Value
FROM YourTable s
SELECT DISTINCT t.* 
FROM tbl
CROSS APPLY (
    VALUES
        (GroupId, FieldName, Value),
        (GroupId, 'UserName', UserName)
) t(GroupId, FieldName, Value)

还可以从我的 post

中查看有关 UNPIVOTVALUES 的一些小信息