如何正确编写UNPIVOT?

时间:2013-04-03 15:01:21

标签: sql sql-server tsql unpivot

有一个表“研究”,列“ID”,“code1”,“code2”,“soc0”,“soc1”......“socn” 其中n = 40。

目前,单元格的值并不重要,因为我需要获取“soc”列的列表,如:

soc0  
soc1   
....  
soc40

你能帮我写一下吗?

3 个答案:

答案 0 :(得分:3)

您可以使用UNPIVOT功能来获取此功能。

基本语法是:

select *
from research
unpivot
(
  value
  for col in (soc0, soc1, soc40)
) un;

请参阅SQL Fiddle with Demo

但您必须输入要取消忽略的所有列名称。如果您不想键入所有列名,则可以使用动态SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.column_name)
         from information_schema.columns as C
         where C.table_name = 'research' and
               C.column_name like 'soc%'
         for xml path('')), 1, 1, '')

set @query 
  = 'select id, col, value
     from research
     unpivot
     (
        value
        for col in ('+ @colsunpivot +')
     ) u'

exec(@query)

请参阅SQL Fiddle with Demo

但是如果你只想要一个列名列表,那么你可以直接查询它而不用univot:

select C.table_name, C.column_name
from information_schema.columns c
where C.table_name = 'research' and
  C.column_name like 'soc%'

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

试试这个

select  unpvt.value
from research c
unpivot ( 
 value 
 for attribute in (Colsoc0,Colsoc1,Colsoc2,..,Colsocn)
) unpvt

答案 2 :(得分:0)

select  *
from    research
unpivot (
        CodeValue for CodeName in (code0, code1, code2)
        ) sub

Example at SQL Fiddle