6

我已经阅读了数十种与我即将提出的类似换位问题的解决方案,但奇怪的是没有一个完全反映我的问题。我只是想在一个简单的仪表板类型数据集中将我的行翻转为列。

从各种事务表中提取的数据如下所示:

DatePeriod  PeriodNumberOverall   Transactions   Customers   Visits

'Jan 2012'   1                    100            50          150
'Feb 2012'   2                    200            100         300
'Mar 2012'   3                    300            200         600

我希望能够生成以下内容:

                      Jan 2012   Feb 2012   Mar 2012

Transactions          100        200        300
Customers             50         100        200
Visits                150        300        600

指标将是静态的(交易、客户和访问),但日期周期将是动态的(IE - 随着月份的推移会增加更多)。

同样,我准备了许多利用 pivot、unpivot、store 过程、UNION ALL 等的示例,但我没有进行任何聚合,只是从字面上转换整个输出。我还在 Visual Studio 2005 中找到了一种使用带有嵌入式列表的矩阵的简单方法,但我无法将最终输出导出到 excel 中,这是必需的。任何帮助将不胜感激。

4

3 回答 3

2

您需要动态创建一个带有PIVOTAPPLY运算符的 SQL 语句,然后运行该命令。如果您的指标是静态的(交易、客户和访问),因此我们可以使用 CROSS APPLY 运算符和 VALUES 作为表源。

对于 SQL Server2008+

DECLARE @cols nvarchar( max),
        @query nvarchar(max)
SELECT @cols =
  STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName                               
         FROM dbo.test62 t                   
         FOR XML PATH(''), TYPE).value ('.', 'nvarchar(max)'), 1, 1, '')     

SET @query =
 'SELECT *
  FROM (
        SELECT t.DatePeriod, COALESCE(o.Transactions, o.Customers, o.Visits) AS PvtVals, o.PvtColumns, o.OrderColumns 
        FROM dbo.test62 t CROSS APPLY (
                                       VALUES(t.Transactions, NULL, NULL, ''Transaction'', 1),
                                             (NULL, t.Customers, NULL, ''Customers'', 2),
                                             (NULL, NULL, t.Visits, ''Visits'', 3)
                                       ) o (Transactions, Customers, Visits, PvtColumns, OrderColumns)
        ) p
  PIVOT
   (      
    MAX(PvtVals) FOR DatePeriod IN (' + @cols + ')
    ) AS pvt
  ORDER BY pvt.OrderColumns '
EXEC(@query) 

结果:

PvtColumns  Jan 2012 Fed 2012 Mar 2012
Transaction 100      200      300
Customers   50       100      200
Visits      150      300      600

SQLFiddle上的演示

对于 SQL Server 2005

DECLARE @cols nvarchar( max),
        @query nvarchar(max)
SELECT @cols =
  STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName                               
         FROM dbo.test62 t                   
         FOR XML PATH(''), TYPE).value ('.', 'nvarchar(max)'), 1, 1, '')     

SET @query =
 'SELECT *
  FROM (
        SELECT t.DatePeriod, COALESCE(o.Transactions, o.Customers, o.Visits) AS PvtVals, o.PvtColumns, o.OrderColumns
        FROM dbo.test62 t CROSS APPLY (
                                       SELECT t.Transactions, NULL, NULL, ''Transaction'', 1
                                       UNION ALL 
                                       SELECT NULL, t.Customers, NULL, ''Customers'', 2
                                       UNION ALL 
                                       SELECT NULL, NULL, t.Visits, ''Visits'', 3
                                       ) o (Transactions, Customers, Visits, PvtColumns, OrderColumns)
        ) p
  PIVOT
   (      
    MAX(PvtVals) FOR DatePeriod IN (' + @cols + ')
    ) AS pvt
  ORDER BY pvt.OrderColumns'
EXEC(@query) 
于 2013-04-02T07:09:41.923 回答
2

为了获得您想要的结果,您首先需要UNPIVOT数据,然后PIVOT the是 DatePeriod` 值。

UNPIVOT 会将 , 的多列Transactions转换CustomersVisits多行。其他答案是使用UNION ALL取消透视,但 SQL Server 2005 是UNPIVOT支持该功能的第一年。

取消透视数据的查询是:

select dateperiod,
  col, value
from transactions
unpivot
(
  value for col in (Transactions, Customers, Visits)
) u

请参阅演示。这会将您当前的列转换为多行,因此数据如下所示:

| DATEPERIOD |          COL | VALUE |
-------------------------------------
|   Jan 2012 | Transactions |   100 |
|   Jan 2012 |    Customers |    50 |
|   Jan 2012 |       Visits |   150 |
|   Feb 2012 | Transactions |   200 |

现在,由于数据在行中,您可以将PIVOT函数应用于DatePeriod列:

select col, [Jan 2012], [Feb 2012], [Mar 2012]
from
(
  select dateperiod,
    t.col, value, c.SortOrder
  from
  (
    select dateperiod,
      col, value
    from transactions
    unpivot
    (
      value for col in (Transactions, Customers, Visits)
    ) u
  ) t
  inner join
  (
    select 'Transactions' col, 1 SortOrder
    union all
    select 'Customers' col, 2 SortOrder
    union all
    select 'Visits' col, 3 SortOrder
   ) c
    on t.col = c.col
) d
pivot
(
  sum(value)
  for dateperiod in ([Jan 2012], [Feb 2012], [Mar 2012])
) piv
order by SortOrder;

请参阅SQL Fiddle with Demo

如果您有未知数量的日期期间,那么您将使用动态 SQL:

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

select @cols = STUFF((SELECT ',' + QUOTENAME(dateperiod) 
                    from transactions
                    group by dateperiod, PeriodNumberOverall
                    order by PeriodNumberOverall
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT col, ' + @cols + ' 
             from 
             (
                select dateperiod,
                  t.col, value, c.SortOrder
                from
                (
                  select dateperiod,
                    col, value
                  from transactions
                  unpivot
                  (
                    value for col in (Transactions, Customers, Visits)
                  ) u
                ) t
                inner join
                (
                  select ''Transactions'' col, 1 SortOrder
                  union all
                  select ''Customers'' col, 2 SortOrder
                  union all
                  select ''Visits'' col, 3 SortOrder
                 ) c
                  on t.col = c.col
            ) x
            pivot 
            (
                sum(value)
                for dateperiod in (' + @cols + ')
            ) p 
            order by SortOrder'

execute(@query)

请参阅SQL Fiddle with Demo。两者都会给出结果:

|          COL | JAN 2012 | FEB 2012 | MAR 2012 |
-------------------------------------------------
| Transactions |      100 |      200 |      300 |
|    Customers |       50 |      100 |      200 |
|       Visits |      150 |      300 |      600 |
于 2013-04-02T10:58:21.433 回答
1

如果您可以提前知道有多少个不同的日期期间,那么您可以使用固定查询,如下所示:


;with CTE_UNIONTable
as 
(
select [DatePeriod],[PeriodNumberOverall],[Transactions] as [value], 'Transactions' as subType from table1
UNION ALL 
select [DatePeriod],[PeriodNumberOverall],[Customers] as [value], 'Customers' as subType from table1
UNION ALL 
select [DatePeriod],[PeriodNumberOverall],[Visits] as [value], 'Visits' as subType from table1
), CTE_MiddleResult
as 
(
select * from CTE_UNIONTable
    pivot 
    (
       max(value) 
       for DatePeriod in ([Jan 2012],[Feb 2012],[Mar 2012])
     ) as P
     )
select SubType, max([Jan 2012]) as [Jan 2012] ,max([Feb 2012]) as [Feb 2012], max([Mar 2012]) as [Feb 2012]
from CTE_MiddleResult
group by SubType

SQL FIDDLE DEMO

如果无法预测有多少个日期周期,那么@Alexander 已经给出了解决方案,下面的代码只是第二种意见,而不是使用APPLY,使用UNION ALL


DECLARE @cols nvarchar( max),
        @query nvarchar (max),
        @selective nvarchar(max)
SELECT @cols =
  STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName                               
         FROM table1 t                   
         FOR XML PATH( ''), TYPE).value ('.', 'nvarchar(max)'),1,1,'')

SELECT @selective =
  STUFF((SELECT ',MAX(' + QUOTENAME(t.DatePeriod) +') as ' + QUOTENAME(t.DatePeriod)  AS ColName                               
         FROM table1 t                   
         FOR XML PATH( ''), TYPE).value ('.', 'nvarchar(max)'),1,1,'')

set @query = '
;with CTE_UNIONTable
as 
(
select [DatePeriod],[PeriodNumberOverall],[Transactions] as [value], ''Transactions'' as subType from table1
UNION ALL 
select [DatePeriod],[PeriodNumberOverall],[Customers] as [value], ''Customers'' as subType from table1
UNION ALL 
select [DatePeriod],[PeriodNumberOverall],[Visits] as [value], ''Visits'' as subType from table1
), CTE_MiddleResult
as 
(
select * from CTE_UNIONTable
    pivot 
    (
       max(value) 
       for DatePeriod in ('+@cols+')
     ) as P
)
select SubType,' + @selective + ' 
from CTE_MiddleResult
group by SubType'

exec(@query)

SQL 小提琴演示

于 2013-04-02T07:29:49.653 回答