如何选择特定的列作为行?

时间:2019-04-09 18:26:48

标签: sql-server

我有2个表Phone_record和customer

在电话记录表中,我有两列company_name和ModelNo 现在我想显示Company_name作为我的主列名称 在本专栏中,我想展示该公司的模型

Company 1                  company2..... 
Model1                     model1
Model2                     model2 

如何编写此查询?

1 个答案:

答案 0 :(得分:0)

这里是如何执行此操作的完整示例。

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

create table #Something
(
    ID int,
    Subject1 varchar(50)
)

insert #Something
select 10868952, 'Some Subject' union all
select 10868952, 'Another one' union all
select 10868952, 'This Subject' union all
select 10868952, 'Science' union all
select 12345, 'My Subject'
declare @MaxCols int

declare @StaticPortion nvarchar(2000) = 
    'with OrderedResults as
    (
        select *, ROW_NUMBER() over(partition by ID order by Subject1) as RowNum
        from #Something
    )
    select ID';

declare @DynamicPortion nvarchar(max) = '';
declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by ID order by ID';

with E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --100 rows
cteTally(N) AS 
(
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E2
)

select @DynamicPortion = @DynamicPortion + 
    ', MAX(Case when RowNum = ' + CAST(N as varchar(6)) + ' then Subject1 end) as Subject' + CAST(N as varchar(6)) + CHAR(10)
from cteTally t
where t.N <= 
(
    select top 1 Count(*)
    from #Something
    group by ID
    order by COUNT(*) desc
)

--select @StaticPortion + @DynamicPortion + @FinalStaticPortion

declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
exec sp_executesql @SqlToExecute