旋转和分区查询以获取名称

时间:2018-11-22 01:16:24

标签: sql sql-server sql-server-2008-r2 row-number

我在下面尝试了HackerRank问题,其中,名称必须在职业上进行定位。

https://www.hackerrank.com/challenges/occupations/problem

我找到了一个解决方案,但是不明白它是如何工作的,为什么当其他名称取最大值时,其他名称又返回结果呢?

表格:

CREATE TABLE Occupations
(
    Name varchar(25),
    Occupation varchar(1000)
)

INSERT INTO Occupations VALUES('Samantha', 'Doctor')
GO
INSERT INTO Occupations VALUES('Julia', 'Actor')
GO
INSERT INTO Occupations VALUES('Maria', 'Actor')
GO
INSERT INTO Occupations VALUES('Meera', 'Singer')
GO
INSERT INTO Occupations VALUES('Ashley', 'Professor')
GO
INSERT INTO Occupations VALUES('Ketty', 'Professor')
GO
INSERT INTO Occupations VALUES('Christeen', 'Singer')
GO
INSERT INTO Occupations VALUES('Jane', 'Actor')
GO
INSERT INTO Occupations VALUES('Jenny', 'Doctor')
GO
INSERT INTO Occupations VALUES('Priya', 'Singer')
GO

解决方案:

SELECT [Doctor], [Professor], [Singer],[Actor] 
FROM 
(   
    SELECT ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name ASC) AS RowNumber, * 
    FROM Occupations) as tempTable 
    PIVOT 
    (
        MAX(Name) FOR OCCUPATION IN ([Doctor], [Professor], [Singer], [Actor])
    ) AS pivotTable

所以我理解执行此查询的方式是:按名称对行进行分区,然后按名称对最大名称进行旋转。那么查询如何仍然按职业返回其他名称?

0 个答案:

没有答案