重新排列SQL Server中的行和列

时间:2011-02-21 05:14:46

标签: sql-server-2005

我正在尝试使用某种方案重新排列列和行的值,但我无法做到这一点。我也尝试使用枢轴。

以下是表格的情景。

enter image description here

1 个答案:

答案 0 :(得分:1)

首先,您搜索的查询类型通常称为交叉表查询。 SQL语言不是为动态列生成而设计的。但是,您可以使用静态列构建查询(我使用CTE使测试更容易。当然,您可以使用派生表执行此操作):

With SampleInputs As
    (
    Select 1 As sbuid, 4216 As fac_Id, 2010 As [Year], 1 As [Month], 10 As Venting, 20 As compustion, 'abcd' As Comment
    Union All Select 2, 4216, 2010, 2, 15, 25, 'XYZ'
    )
    , FlattenedData As
    (
    Select fac_id, [Year], [Month], Venting As Value, 'Venting' As [Type]
    From SampleInputs
    Union All
    Select fac_id, [Year], [Month], Compustion, 'Compustion'
    From SampleInputs
    )
Select fac_id, [Type]
    , Sum( Case When [Year] = 2010 And [Month] = 1 Then Value End ) As [Jan-2010]
    , Sum( Case When [Year] = 2010 And [Month] = 2 Then Value End ) As [Feb-2010]
From FlattenedData 
Group By fac_id, [Type]

如果要动态构建此查询,则不应在T-SQL中执行此操作。相反,您应该在中间层组件或报告工具中构建查询。