在SQL Server中透视列

时间:2015-04-23 07:39:26

标签: sql-server

我有以下结果集(忽略列名,修改为以列的形式显示),这是使用给定的查询生成的

Source RfrshCycleId SorceType CycleNmber CycleNme sltme RfrshCycleDetalId PublishTime
-------------------------------------------------------------------------  
Mercury 1   Summary 1   Cycle1  3:00:00 NULL    NULL
Mercury 2   Summary 3   Cycle3  6:00:00 1   4/21/15 4:32 AM
Mercury 3   Summary 5   Cycle5  10:00:00    NULL    NULL
Mercury 4   Summary 2   Cycle2  15:00:00    NULL    NULL
Mercury 5   Detail  1   Cycle1  8:00:00 NULL    NULL
Mercury 6   Detail  2   Cycle2  23:00:00    NULL    NULL
Mercury 7   Complete    1   Cycle1  3:00:00 2   4/18/15 1:42 AM
Mercury 8   Complete    3   Cycle3  6:00:00 NULL    NULL
Mercury 9   Complete    2   Cycle2  15:00:00    NULL    NULL
Mercury 10  Complete    4   Cycle4  18:00:00    NULL    NULL

用于获得上述结果集的查询是:

SELECT 
    RC.Source As Source, RC.RefreshCycleId As RefreshCycleId,
    RC.SourceType As SourceType, RC.CycleNumber As CycleNumber,
    RC.CycleName As CycleName, RC.slatime As slatime,
    RCD.RefreshCycleDetailId As RefreshCycleDetailId,
    RCD.PublishTime As PublishTime
FROM
    RefreshCycles RC
FULL OUTER JOIN 
    RefreshCycleDetails RCD ON RC.RefreshCycleId = RCD.RefreshCycleID
WHERE 
    RC.Source = 'Mercury'

我希望得到如下结果集

pivoting in excel

我尝试了解析,然后转动结果集,但是对于pivot / unpivot来说是新的,无法获得正确的结果。请帮助。

1 个答案:

答案 0 :(得分:1)

您无法使用SQL Server执行此操作,并且有充分的理由。这是数据存储和数据表示之间区别的典型示例。您最初以标准化形式保存数据的反应是正确的。您应该调查创建链接服务器到Excel文档以创建矩阵报告,或者当然有SSRS,这需要更多参与并需要更多工作来设置。