Пример отмены SQL - PullRequest
       11

Пример отмены SQL

0 голосов
/ 12 октября 2018

Прямо сейчас у меня есть следующая таблица, и я хочу ее отключить, чтобы мои столбцы и строки были перевернуты, как показано ниже - спасибо!

ЕСТЬ

текущий

ХОЧУ

хочу

1 Ответ

0 голосов
/ 12 октября 2018

Этот пример в Transact-SQL.Синтаксис Oracle (11g +) похож, но с несколькими дополнительными опциями, такими как обработка нулевых значений.

-- setting up a table variable with your starting data
declare @t table 
    (  Name         varchar(10) primary key 
      ,[Age 18-24]  int
      ,[Age 25-34]  int
      ,[Age 35-44]  int  );

insert @t (Name, [Age 18-24], [Age 25-34], [Age 35-44])
values   ('John', 1, 0, 0 )
        ,('Maria', 0, 0, 1 )
        ,('June' , 0, 0, 1 )

--- the actual query starts here 

select [Name], [Column], [Value]
from 
    (   -- select relevant columns from source 
        select Name, [Age 18-24], [Age 25-34], [Age 35-44]
        from @t
    ) as piv
UNPIVOT
    (   -- define new result columns.  
        ----  [Value] is the detailed count/sum/whatever
        ----  [Column] get the old name of the column 

        [Value] 
        for [Column] in ([Age 18-24], [Age 25-34], [Age 35-44]) 
    ) as unpiv
...