我有这样的结果集:
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个房主。
答案 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小提琴
答案 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>;
我不认为你可以转动,因为你没有进行任何聚合