将行值转换为列

时间:2018-02-13 04:07:37

标签: sql toad

我有一个示例查询返回:

First screenshot

查询是:

SELECT departmentID, departmentMembers, workingHours
FROM timeTracker
WHERE departmentID = 11111

基本上,我想转置departmentMembers列的值并将它们设置为新列,workingHours的每列的值将是这些列的值。请参阅第二个屏幕截图,了解我的需求。 请注意,以下屏幕截图中不再显示departmentMembers列:

Second Screenshot

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select departmentID, 
       sum(case when departmentMembers = 'ADMIN_FEE' then workingHours else 0 end) as admin_fee,
       . . .
from timeTracker
where departmentID = 11111
group by departmentID;

. . .用于其余列。

答案 1 :(得分:0)

使用数据透视表转置列

select departmentID, [ADMIN_FEE],[AGT_COMM],[AGT_OVER],[IRPM],[NCB_A],[VIP_FEE] from (SELECT departmentID, departmentMembers, workingHours FROM timeTracker WHERE departmentID = 11111) as SourceTable Pivot (max(workingHours) for departmentMembers IN ([ADMIN_FEE],[AGT_COMM],[AGT_OVER],[IRPM],[NCB_A],[VIP_FEE]) AS PivotTable;