具有非整数值的数据透视表,没有聚合函数

时间:2018-08-05 00:39:12

标签: sql-server

我需要根据行中具有名称的职业获得结果。下面是示例数据的结构。

create table Employees (name varchar(10), occupation varchar(12))

Insert into Employees values ('Member1','Doctor')
Insert into Employees values ('Member2','Doctor')
Insert into Employees values ('Member3','Lawyer')
Insert into Employees values ('Member4','Teacher')
Insert into Employees values ('Member5','Lawyer')
Insert into Employees values ('Member6','Teacher')
Insert into Employees values ('Member7','Lawyer')

根据我的理解,它可以在SQL Server中用PIVOT实现,但是它需要一些聚合函数,并且我可以使用MAX,它将得到MAX(value1)= value1 我在下面的查询中尝试过:

Select * from 
(Select name,occupation from Employees) as emp
PIVOT 
(
  MAX(name) for occupation in (Doctor,Teacher,Lawyer)
) as pvt

它给我的结果是

Doctor  Teacher Lawyer
Member2 Member6 Member7

但是我需要以下结构的结果,因为列是按升序排列的

Doctor  Teacher Lawyer
Member1 Member4 Member3
Member2 Member6 Member5
NULL    NULL    Member7

2 个答案:

答案 0 :(得分:1)

美好的一天,

请检查此解决方案:

Select * 
from (
    Select 
        [name],[occupation], 
        RN = ROW_NUMBER() OVER (partition by [occupation] order by [name],[occupation])
    from Employees
) t
PIVOT (
    MAX(name) for occupation in (Doctor,Teacher,Lawyer)
) as pvt

答案 1 :(得分:0)

使用ROW_NUMBER()函数并尝试以下方式

 Select * 
    from (
        Select 
            name,occupation, 
            Row_num = ROW_NUMBER() OVER (partition by [occupation] order by [name],[occupation])
        from Employees
    ) t
    PIVOT (
        MAX(name) for occupation in (Doctor,Teacher,Lawyer)
    ) as pvt

http://sqlfiddle.com/#!18/41f11/1

Row_num Doctor  Teacher Lawyer
1       Member1 Member4 Member3
2       Member2 Member6 Member5
3      (null)   (null)  Member7