SQL Server - 将列转换为行

Kri*_*aya 1 sql sql-server

我有一个表格,简单的选择发出如下所示

在此输入图像描述

我想写一个select语句输出如下

在此输入图像描述

有人能帮我吗...

Tar*_*ryn 8

因为你基本上旋转你当前的列Sale,IncomeProfit进入行,然后将month值列,那么你会想先unpivot的当前列,然后转动的月份.

根据您的SQL Server版本,有几种方法可以取消数据的显示.您可以使用UNPIVOT功能或CROSS APPLY:

select month, type, value
from yourtable
cross apply
(
  select 'Sale', sale union all
  select 'Income', Income union all
  select 'Profit', Profit
) c (type, value)
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.这会将您当前的数据转换为:

| MONTH |   TYPE | VALUE |
|-------|--------|-------|
|   Jan |   Sale |   100 |
|   Jan | Income |    50 |
|   Jan | Profit |    10 |
|   Feb |   Sale |    20 |
|   Feb | Income |    40 |
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用PIVOT函数将月份转换为列标题.

select type, Jan, Feb, Mar, Apr
from
(
  select month, type, value
  from yourtable
  cross apply
  (
    select 'Sale', sale union all
    select 'Income', Income union all
    select 'Profit', Profit
  ) c (type, value)
) d
pivot
(
  sum(value)
  for month in (Jan, Feb, Mar, Apr)
) piv;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.

如果您有未知的月数,那么您可以使用动态SQL:

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

select @cols = STUFF((SELECT distinct N',' + QUOTENAME(Month) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT type, ' + @cols + N' 
            from 
            (
                select month, type, value
                from yourtable
                cross apply
                (
                  select ''Sale'', sale union all
                  select ''Income'', Income union all
                  select ''Profit'', Profit
                ) c (type, value)
            ) x
            pivot 
            (
                sum(value)
                for month in (' + @cols + N')
            ) p '

execute sp_executesql @query;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo