2017-03-06 111 views
-1

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

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 
+0

你想这显示在SQL Management Studio或在应用程序的用户界面? –

+0

你想要一个PIVOT查询吗?看看是否有帮助:https://technet.microsoft.com/fi-fi/library/ms177410(v=sql.105).aspx – Sami

回答

0
create table #TestTable (id int, name varchar(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 
(
    select * 
    from #TestTable 
) src 
pivot 
(
    max(name) 
    for id in ([1], [2], [3],[4]) 
) piv; 

输出

1   2  3    4 
John Mckensy Valneech Zeebra 
0

您还可以使用动态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);