0

a have a table "research" with columns "ID", "code1", "code2", "soc0", "soc1" ... "socn" where n = 40.

The values of cells are not important at the moment as I need to get a list of "soc" columns like:

soc0  
soc1   
....  
soc40

Can you please help me to write unpivot query?

4

3 回答 3

3

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

基本语法是:

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

请参阅带有演示的 SQL Fiddle

但是您必须输入所有要取消透视的列名。如果您不想键入所有列名,那么您可以使用动态 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

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

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

于 2013-04-03T15:09:24.680 回答
1

尝试这个

select  unpvt.value
from research c
unpivot ( 
 value 
 for attribute in (Colsoc0,Colsoc1,Colsoc2,..,Colsocn)
) unpvt
于 2013-04-03T15:16:55.040 回答
0
select  *
from    research
unpivot (
        CodeValue for CodeName in (code0, code1, code2)
        ) sub

SQL Fiddle 上的示例

于 2013-04-03T15:05:12.370 回答