sql中的pivot字符变量

时间:2018-06-18 07:28:19

标签: sql sql-server tsql pivot

为了在sql server中转移表,我再一次遇到了限制。假设以下占用表包含3个特征,即ID,FirstName和Occupation,如下所示:

Occupation Table

然后,为了根据其职业返回枢轴基础,我尝试了以下代码:

select actress,
       Dancer,
       Photographer,
       Salesman
       from Occupation o 
       pivot (max(o.FirstName) for o.Occupation in ([Actress], [Dancer], [Photographer], [Salesman])) as pivotable

Pivot

虽然结果也返回NULL值。我想在这里想要实现的是,枢轴只包含基于其职业的人名,而不返回所有Null,如下表所示。请任何知道的人,我最诚挚的问候。

Target Result

4 个答案:

答案 0 :(得分:3)

问题是,在你的数据中,每个人之间没有任何关系,所以它不能显示在同一行上(你想在同一行上看到Juli和Satria的链接是什么?)。

如果您可以按每个作业生成行号,则可以按照每个作业的基本位置将它们混合在一起。

IF OBJECT_ID('tempdb..#Jobs') IS NOT NULL
    DROP TABLE #Jobs

CREATE TABLE #Jobs (
    ID INT,
    Name VARCHAR(100),
    Job VARCHAR(100))

INSERT INTO #Jobs (
    ID,
    Name,
    Job)
VALUES
    (1001, 'Satria', 'Dancer'),
    (1002, 'Juli', 'Actress'),
    (1003, 'Mario', 'Actress'),
    (1004, 'Memet', 'Salesman'),
    (1005, 'Alan', 'Photographer'),
    (1006, 'Kiky', 'Photographer'),
    (1007, 'Chacha', 'Photographer'),
    (1008, 'Joko', 'Actress'),
    (1009, 'Juni', 'Dancer'),
    (1010, 'Putra', 'Salesman')



;WITH JobNumbering AS
(
    SELECT
        J.Job,
        J.Name,
        Ranking = ROW_NUMBER() OVER (PARTITION BY J.Job ORDER BY J.ID)
    FROM
        #Jobs AS J
)
SELECT
    P.Actress,
    P.Dancer,
    P.Photographer,
    P.Salesman
FROM
    JobNumbering AS J
    PIVOT (
        MAX(J.Name) FOR J.Job IN ([Actress], [Dancer], [Photographer], [Salesman])
    ) AS P

答案 1 :(得分:2)

您应该首先使用row_number函数

在pivot的源表部分中以所需的方式对它们进行排序

See working demo

select 
    actress,
    Dancer,
    Photographer,
    Salesman
from 
(
select 
   FirstName,
   Occupation,-- see no Id here in select list to explicitly avoid ordering by id
   rn= row_number() over (partition by Occupation order by id asc)
from 
Occupation 
)  o 
pivot 
(
    max(o.FirstName) 
    for o.Occupation in 
    (
        [Actress], [Dancer], [Photographer], [Salesman]
    )
) as pivotable
order by rn --explicitly added to get desired results

答案 2 :(得分:1)

您只需从职业表中选择所需的列。使用CTE或派生表来做到这一点。

select actress,
       Dancer,
       Photographer,
       Salesman
from   (
              select FirstName, Occupation 
              from Occupation 
       ) o 
       pivot 
       (
              max(o.FirstName) 
              for o.Occupation in ([Actress], [Dancer], [Photographer], [Salesman])
       ) as pivotable

答案 3 :(得分:1)

select 
-- incase u dont want null to be populated as a value in the output
  isnull(dancer,' ') as dancer,
  isnull(actress,' ') as actress,
  isnull(salesman,' ') as salesman,
  isnull(photographer,' ') as photographer
from
(
 select firstname,
 occupation,
 row_number() over (partition by occupation order by occupation) as ranks
 from Occupation
) a
pivot
(
min(firstname)
for occupation in ([Dancer],[actress],[salesman], [photographer])
) as piv
order by ranks