转换行到列SQL Server 2008中
问题描述:
表名称是的UserData和名称列PRIMARY KEY,我有一个查询返回以下 像转换行到列SQL Server 2008中
选择名称,jobProfile从的UserData
name | jobProfile
a | Admin b | user c | employee d | Admin e | user f | user g | employee
我想使结果如此(如果可能的话)
user | employee | Admin ___________________________ b | c | a e | g | d f | null | null
答
既然你没有提供非常多的信息,或者说治理改造的任何规则,唯一的答案,我可以给是检查出PIVOT功能。
答
不知道我明白为什么人们试图解决这个问题。似乎对我来说是合法的问题,而不完全是引用问题的重复。引用的问题有3列作为输入,而这个问题有两个。所以需要一个额外的技巧。
-- test data
declare @UserData table (Name varchar(10), JobProfile varchar(10))
insert @UserData
values
('a' , 'Admin'),
('b' , 'user'),
('c' , 'employee'),
('d' , 'Admin'),
('e' , 'user'),
('f' , 'user'),
('g' , 'employee')
-- query
select [user], [employee], [Admin]
from
(
select *, row_number() over (partition by JobProfile order by Name) RowNumber
from @UserData
) as p
pivot
(
min(Name) for JobProfile in ([user], [employee], [Admin])
) as t
order by RowNumber
输出:
user employee Admin
---------- ---------- ----------
b c a
e g d
f NULL NULL
为什么'B','C',并在输出相同的行'了'?也就是说,哪些规则管理着转型? – Oded 2011-06-11 18:12:34
@Oded - 从我所能看到的'job profile'列中的唯一值定义输出列。列中的值对应于输入的“name”列。 – 2011-06-11 18:16:42
@Alex - 是的,我看到了。例如,仍然没有解释为什么'f','c'和'd'在不同的行中。 – Oded 2011-06-11 18:19:31