0

我有一个这样的结果集:

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 个所有者。

4

2 回答 2

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按照建议显示在 join 语句中。更新的 SQL Fiddle

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

于 2012-07-11T20:55:18.877 回答
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>;

我不认为你可以旋转,因为你没有做任何聚合

于 2012-07-11T20:06:32.533 回答