2017-03-06 60 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);