我有一个只有两列的表:
Table: Employees
+----------+-------------+
|Employee | Designation |
+----------+-------------+
| Ron | Manager |
| James | HR |
| Toby | Clerk |
| Amanda | Clerk |
| Jenny | Manager |
| Quentin | HR |
| Roger | Manager |
| Harry | Clerk |
| Sunny | Clerk |
| Rachael | Manager |
+----------+-------------+
我需要编写查询以输出如下结果:
+-----------+--------- +------------+
| Manager | HR | Clerk |
+-----------+----------+------------+
| Jenny | James | Amanda |
| Rachael | Quentin | Harry |
| Roger | null | Sunny |
| Ron | null | Toby |
+-----------+----------+------------+
必须根据员工的名称将其分为不同的列,并按字母顺序排列。网上有解决方案,但是大多数解决方案要么使用此数据创建一个带有id列的新表,以解决问题。是否有一种简单的SQL查询解决方案来解决此问题,而无需创建任何新表?
答案 0 :(得分:2)
您可以使用row_number()
和某种类型的透视。我更喜欢条件聚合:
select max(case when designation = 'Manager' then employee end) as Manager,
max(case when designation = 'HR' then employee end) as HR,
max(case when designation = 'Clerk' then employee end) as Clerk
from (select e.*,
row_number() over (partition by designation order by employee) as seqnum
from employees e
) e
group by seqnum
order by seqnum;