水平显示输出的Sql查询

水平显示输出的Sql查询,sql,sql-server,Sql,Sql Server,我需要以水平方式显示查询输出。我有一些示例数据 create table TestTable (id number, name varchar2(10)) insert into TestTable values (1, 'John') insert into TestTable values (2, 'Mckensy') insert into TestTable values (3, 'Valneech') insert into TestTable valu

我需要以水平方式显示查询输出。我有一些示例数据

create table TestTable (id number, name varchar2(10))
    insert into TestTable values (1, 'John')
    insert into TestTable values (2, 'Mckensy')
    insert into TestTable values (3, 'Valneech')
    insert into TestTable values (4, 'Zeebra')
    select * from TestTable
这将在垂直视图中获取输出

ID Name
==========
1  John
2  Mckensy
3  Valneech
4  Zeebra
但是,我需要水平显示它

ID   1    2       3        4
Name John Mckensy Valneech Zeebra
输出

1         2       3             4
John    Mckensy Valneech    Zeebra

您还可以使用动态sql查询,如下所示

查询

declare @sql as varchar(max);
select @sql = 'select ' + char(39) + 'Name' + char(39) + ' Id,' + stuff((
        select 
        ',max(case [Id] when ' + cast(id as varchar(10)) + '  then name end) ['  
       +  cast([Id] as varchar(10)) + ']'
        from TestTable
        for xml path('')
    ), 1, 1, '');

select @sql += 'from TestTable;';
exec(@sql);

您想在sql management studio或应用程序的ui中显示此信息?您想使用透视查询吗?看看这是否有帮助:
declare @sql as varchar(max);
select @sql = 'select ' + char(39) + 'Name' + char(39) + ' Id,' + stuff((
        select 
        ',max(case [Id] when ' + cast(id as varchar(10)) + '  then name end) ['  
       +  cast([Id] as varchar(10)) + ']'
        from TestTable
        for xml path('')
    ), 1, 1, '');

select @sql += 'from TestTable;';
exec(@sql);