我正在寻找一种在MS SQL服务器中将行转换为列的有效方法。
示例数据库表:
**ID PersonID Person201Code Person201Value**
1 1 CurrentIdNo 0556
2 1 FirstName Queency
3 1 LastName Sablan
查询结果应如下所示:
**CurrentIdNo FirstName LastName**
0556 Queency Sablan
我尝试使用PIVOT,但它只在行值上返回null:
SELECT CurrentIdNo, FirstName, LastName
FROM
(
SELECT ID, PersonId, Person201Code, Person201Value
FROM HRPerson201
) src
PIVOT
(
MAX (ID)
FOR Person201Code in (CurrentIdNo, Firstname, LastName))
pvt;
如何在MS SQL服务器中成功将行转换为列? 谢谢!
答案 0 :(得分:3)
从数据透视表源查询中删除ID
并添加Person201Value
数据透视聚合
而不是ID
SELECT CurrentIdNo,
FirstName,
LastName
FROM (SELECT PersonId,
Person201Code,
Person201Value
FROM HRPerson201) src
PIVOT ( Max (Person201Value)
FOR Person201Code IN (CurrentIdNo,
Firstname,
LastName)) pvt;
答案 1 :(得分:1)
SELECT *
FROM
(SELECT personid,Person201Code,Person201Value
FROM #pivot) Sales
PIVOT(max(Person201Value)
FOR Person201Code in (CurrentIdNo, Firstname, LastName))
AS PivotSales;