Sql-Server

MSQL - 將行切換到列

  • February 16, 2021

我已經被困在下面很長一段時間了,看起來它應該相對簡單,但我不能完全理解它。

您只得到一行,因為沒有其他列/值可以PIVOT產生不同的組。

嘗試:

SELECT 
 Doctor
,Actor
,Singer
,Professor
FROM   
(
 SELECT
   ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) AS Dummy
  ,Name
  ,Occupation
 FROM 
   Occupations
) o 
PIVOT  
 (  
   MAX(Name) FOR Occupation IN (Doctor, Actor, Singer, Professor)  
 ) AS pvt  

您缺少的是可以分組的行。Row_NUMBER是一個很好的解決方案

CREATE TABLE OCCUPATIONS
    (Name varchar(255), Occupation varchar(255))
;

INSERT INTO OCCUPATIONS
    (Name, Occupation)
VALUES
    ('Samantha', 'Doctor'),
    ('Julia', 'Actor'),
    ('Maria', 'Actor'),
    ('Meera', 'Singer'),
    ('Ashely', 'Professor'),
    ('Ketty', 'Professor'),
    ('Christeen', 'Professor'),
    ('Jane', 'Actor'),
    ('Jenny', 'Doctor'),
    ('Priya', 'Singer')
  ;
GO
SELECT Row#,Doctor, Actor, Singer, Professor
from
(
  select Name, Occupation,
ROW_NUMBER() OVER(PARTITION BY Occupation ORDER BY name ASC) AS Row#
  from OCCUPATIONS
) d
pivot
(
  max(Name)
  for Occupation in (Doctor, Actor, Singer, Professor)
 ) piv;
GO
行# | 博士 | 演員 | 歌手 | 教授
---: | :------- | :---- | :----- | :--------
 1 | 珍妮 | 簡 | 米拉 | 阿什利 
 2 | 薩曼莎 | 朱莉婭 | 普里亞 | 克里斯汀
 3 | *空* | 瑪麗亞 | *空* | 凱蒂 
WITH CTE as (SELECT
Name, Occupation,
ROW_NUMBER() OVER(PARTITION BY Occupation ORDER BY name ASC) AS Row#
FROM OCCUPATIONS)
SELECT Row#,Doctor, Actor, Singer, Professor
from
(
  select Name, Occupation,Row#
  from CTE
) d
pivot
(
  max(Name)
  for Occupation in (Doctor, Actor, Singer, Professor)
 ) piv;
GO
行# | 博士 | 演員 | 歌手 | 教授
---: | :------- | :---- | :----- | :--------
 1 | 珍妮 | 簡 | 米拉 | 阿什利 
 2 | 薩曼莎 | 朱莉婭 | 普里亞 | 克里斯汀
 3 | *空* | 瑪麗亞 | *空* | 凱蒂 

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/285126