PIVOT表中的多个varchar行

时间:2015-12-10 09:42:50

标签: sql sql-server tsql

这是我的表值:

enter image description here

我想用这张表做透视。结果应采用格式

示例输出:

print

我尝试了以下内容,

print("Copying... ", end="", flush=True)
shutil.copytree(src, dest)
print("DONE")

但是,它只返回一行。因为 MAX

我怎样才能做到这一点,

1 个答案:

答案 0 :(得分:1)

您可以添加ROW_NUMBER列:

WITH cte AS
(
  SELECT *
  FROM (SELECT *, r = ROW_NUMBER() OVER(PARTITION BY occupation ORDER BY name)
        FROM  #Occupations) AS s
  PIVOT
  (
    MAX(name)
    FOR occupation IN (Doctor, Professor, Singer, Actor)
  )pvt
)
SELECT Doctor, Professor, Singer, Actor
FROM cte;

LiveDemo

输出:

╔══════════╦═══════════╦════════╦═══════╗
║  Doctor  ║ Professor ║ Singer ║ Actor ║
╠══════════╬═══════════╬════════╬═══════╣
║ Jenny    ║ Ashley    ║ Meera  ║ Jane  ║
║ Samantha ║ Christeen ║ Priya  ║ Julia ║
║          ║ Ketty     ║        ║ Maria ║
╚══════════╩═══════════╩════════╩═══════╝