枢轴表概念

时间:2017-11-19 16:59:52

标签: sql sql-server sql-server-2008

这是我的表格输入

Name      Occupation
----------------------
Ashley    Professor 

Samantha  Actor 

Julia     Doctor 

Britney   Professor 

Maria     Professor 

Meera     Professor 

Priya     Doctor 

Priyanka  Professor 

Jennifer  Actor

Ketty Actor 
.
.
.

Christeen Singer 

Eve Actor 

Aamina Doctor 

输出

Doctor   Professsor singer     Actor
-----------------------------------------------
Aamina   Ashley   Christeen    Eve 

Julia   Belvet   Jane          Jennifer

Priya   Britney  Jenny         Ketty 

NULL    Maria    Kristeen      Samantha

NULL    Meera    NULL          NULL 

NULL    Naomi    NULL          NULL 

IN输出标题不应显示,即医生,歌手,...... 这是我的问题,我可以通过使用Case语句来做到这一点。但剧本花了很长时间。所以有人帮助在sql server

中使用Pivot概念来显示输出

1 个答案:

答案 0 :(得分:0)

我觉得这样的事情就是你想要的。我使用4个常用表表达式(CTE)来获取每个职业的名称。我在每个CTE中都有一个Windows函数来命令名称并为每个名称分配一个Id。我加入Id的所有CTE,你就得到了结果。

WITH doctor AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Occupation 
                    ORDER BY [Name]) AS Id,[Name],Occupation
FROM your_Table
WHERE Occupation = 'Doctor'),

professor AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Occupation 
                    ORDER BY [Name]) AS Id,[Name],Occupation
FROM your_Table
WHERE Occupation = 'Professor'),

singer AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Occupation 
                    ORDER BY [Name]) AS Id,[Name],Occupation
FROM your_Table
WHERE Occupation = 'Singer'),

actor AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Occupation 
                    ORDER BY [Name]) AS Id,[Name],Occupation
FROM your_Table
WHERE Occupation = 'Actor')

SELECT d.Name AS 'Doctor',p.Name AS 'Professor',
        s.Name AS 'Singer',a.Name AS 'Actor'
FROM doctor d
     FULL OUTER JOIN professor p ON d.Id = p.Id
     FULL OUTER JOIN singer s ON p.Id = s.Id
     FULL OUTER JOIN actor a ON s.Id = a.Id

结果:

+--------+-----------+-----------+----------+
| Doctor | Professor |  Singer   |  Actor   |
+--------+-----------+-----------+----------+
| Aamina | Ashley    | Christeen | Eve      |
| Julia  | Belvet    | Jane      | Jennifer |
| Priya  | Britney   | Jenny     | Ketty    |
| NULL   | Maria     | Kristeen  | Samantha |
| NULL   | Meera     | NULL      | NULL     |
| NULL   | Naomi     | NULL      | NULL     |
| NULL   | Priyanka  | NULL      | NULL     |
+--------+-----------+-----------+----------+