sql select query将第1列转换为标题,将第2列转换为行?

时间:2013-09-20 17:35:35

标签: sql sql-server sql-server-2008

是否可以将第1列转换为标题,将第2列转换为行?请在下面找一个例子

   Type  | qty  (Header)
  Apple    4
  Orange   10
  Grapes   5


Apple | Orange | Grapes (Header)
4       10         5       

2 个答案:

答案 0 :(得分:0)

在SQL Server中,存在STUFF()和EXEC()函数以进行相同的动态查询。

select @script = STUFF( SELECT qty + ' AS ' + type + ', ' from table_orig);

EXEC (@script);

在MySql中,您可以使用EXECUTE:

SET @sqltxt = null;
SELECT GROUP_CONCAT(CONCAT( qty, ' AS ', type, ' ') ) INTO @sqltxt
FROM table_orig;

SET @sqltxt = concat('SELECT ', @sqltxt , ' FROM DUAL');

PREPARE stmt FROM @sqltxt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
祝你好运,

答案 1 :(得分:0)

- 只需使用一些样本

create table #fruits ([type] varchar(10), quantity int)
insert into #fruits select  'Apple',4 union all select 'Orange', 10 union all select 'Grapes', 5

- 首先获取唯一[结果] s

的集合
declare @sqlStr varchar(max)

select @sqlStr = '['+ 
replace(
stuff((select distinct ','+[type] as [text()]
from #fruits s
    for xml path ('')) ,1,1,'')
    ,',','],[') + ']' 
from #fruits s1

select @sqlStr

- 汇编动态查询

declare @sqlStr1 varchar(max)
set @sqlStr1 = 'select *
from #fruits  a
pivot (sum (quantity) for [type] in ('+@sqlStr+')
    ) p'

- 运行动态查询

 exec (@sqlStr1)    

希望这会有所帮助

创建永久会议桌的补充

declare @sqlStr1 varchar(max)
set @sqlStr1 = 'IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[TblFruits]'') AND type in (N''U''))
DROP TABLE [dbo].[TblFruits]

select *
into TblFruits
from #fruits a
pivot (sum (quantity) for [type] in ('+@sqlStr+')
        ) p'

-- run dynamic query
 exec (@sqlStr1)