我正在尝试在一张表中转置一些数据,但是由于我找不到使用varchar列的方法,所以我无法完成这个操作。我有这样一张表:
declare @table table(name VARCHAR(50) not null, occupation VARCHAR(MAX))
insert into @table values ('A','Doctor')
insert into @table values ('B','Doctor')
insert into @table values ('A','Professor')
insert into @table values ('A','Singer')
insert into @table values ('A','Actor')
SELECT
CASE WHEN occupation = 'Doctor' THEN NAME END AS Doctor,
CASE WHEN occupation = 'Professor' THEN NAME END AS Professor,
CASE WHEN occupation = 'Singer' THEN NAME END AS Singer,
CASE WHEN occupation = 'Actor' THEN NAME END AS Actor
FROM @table
输出:
Doctor Professor Singer Actor
A NULL NULL NULL
B NULL NULL NULL
NULL A NULL NULL
NULL NULL A NULL
NULL NULL NULL A
对于 Pivot,我得到了这个输出:
select * from
(
select name, occupation from @table ) src
pivot (
min(name)
for occupation in ([Doctor],[Professor],[Singer],[Actor])) as pvt
Doctor Professor Singer Actor
A A A A
针对min/max/function函数,pivot函数只给我部分输出结果,而对于count函数,我只能得到医生、歌手等职业的记录数,但我需要实际的数据行,而不是行数统计。
我所需要的是:
Doctor Professor Singer Actor
A A A A
B NULL NULL NULL
即,假设我们有5个医生的姓名,我们需要在医生列中显示5个条目。
row_number()
的order by
子句中使用order by name
。 - Gordon Linoffgroup by
的作用。内部查询计算每个名称在“列列表”中的位置。然后,外部查询根据位置创建这些列表。 - Gordon Linoff