SQL SERVER 2008中的PIVOT结果集

时间:2012-07-11 19:52:57

标签: sql-server

我有这样的结果集:

SELECT PropertyId, Owner from Table A

PropertyId    Owner

  1          Company A
  1          Company B

I want to Pivot the result set like this:

PropertyId  Owner 1 Owner 2

 1           CompanyA Company B

换句话说,我希望每个房产都有2个房主。假设每个房产都有最多2个房主。

2 个答案:

答案 0 :(得分:2)

我创建的查询只有问题是,如果只有1个所有者,它将不显示propertyid,但它将使用空值。

;With [CTE] as (
  Select
    [PropertyId]
    ,[Owner]
    ,Row_Number()
      Over(Partition by [PropertyId] Order by [Owner]) as [RN]
  From [TableA]
)
Select
  a.[PropertyId]
  ,a.[Owner] as [Owner1]
  ,b.[Owner] as [Owner2]
From [CTE] as a
    Left Join [CTE] as b on a.[PropertyId] = b.[PropertyId]
        And b.[RN] = 2
Where a.[RN] = 1
    --And b.[RN] = 2

修改 更新为按建议在联接语句中显示b.[RN] = 2。更新了SQL小提琴

SQL小提琴:http://sqlfiddle.com/#!3/5af8c/7

答案 1 :(得分:0)

SELECT <non-pivoted column>,

[first pivoted column] AS <column name>,

[second pivoted column] AS <column name>,

...

[last pivoted column] AS <column name>

FROM

(<SELECT query that produces the data>)

AS <alias for the source query>

PIVOT

(

**<aggregation function>(<column being aggregated>)**

FOR

[<column that contains the values that will become column headers>]

IN ( [first pivoted column], [second pivoted column],

... [last pivoted column])

) AS <alias for the pivot table>

<optional ORDER BY clause>;

我不认为你可以转动,因为你没有进行任何聚合