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 人しかいない場合、プロパティ ID が表示されず、null 値で機能することです。

;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

于 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 に答える