具有现有 sql 查询的多个数据透视表包含数据透视表

Multiple Pivot with an existing sql query working contains pivot

我有一个使用 Pivot 的 SQL 查询, 我有一些计划记录 (table Plan),每个计划我每个月都有一个金额 (table PlanMonth)。 这是它如何与 pivot 一起使用的示例。

select PlanId,[1]    Jan,[2]Feb,[3]Mar,[4]Apr,[5]May,[6]Jun,[7] July,[8]Aug,[9]Sep,[10]Oct,[11]Nov,[12] Dec
from(
select Plan.Id PlanId,PlanMonth.Amount,PlanMonth.Month 
from PlanTable

left join PlanMonth on
LockAmount.IdPlan = rpo.Id
)p
PIVOT
(
SUM (Amount)
FOR Month IN
( [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS pvt 

我想从另一个由 IdPlan 链接的 table (LockAmount table) 添加更多列 这是示例:

select PlanId,[1] LockAmount1,[2] LockAmount2,[3] LockAmount3,[4] LockAmount4 
from(
select Plan.Id PlanId,LockAmountTable.LockAmount,LockAmountTable.NumForecast 
from PlanTable

left join LockAmountTable on
LockAmount.IdPlan = rpo.Id
)p
PIVOT
(
SUM (LockAmount)
FOR NumForecast IN
( [1][1],[2],[3],[4])
) AS pvt

这就是 table 结构的完成方式

我的问题是如何应用多个数据透视表以这种形式显示数据

根据我从问题中了解到的情况,我们是否可以拥有多个支点并希望使用共享的查询进行集成。是的,我们可以采用 CTE 的方法,直到 sub-queries 中出现相同的列。以下是可能有用的查询。

; with pivot_1 as
(
select pvt1.PlanId as pvt1PlanID,pvt1.[1] Jan,pvt1.[2]Feb,pvt1.[3]Mar,pvt1.[4]Apr,pvt1.[5]May,pvt1.[6]Jun,pvt1.[7] July,pvt1.[8]Aug,pvt1.[9]Sep,pvt1.[10]Oct,pvt1.[11]Nov,pvt1.[12] Dec
from(
select Plan.Id PlanId,PlanMonth.Amount,PlanMonth.Month 
from PlanTable
left join PlanMonth on
LockAmount.IdPlan = rpo.Id
)p
PIVOT
(
SUM (Amount)
FOR Month IN
( [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS pvt1
), pivot_2 as (
select pvt2.PlanId as pvt2PlanID,pvt2.[1] LockAmount1,pvt2.[2] LockAmount2,pvt2.[3] LockAmount3,pvt2.[4] LockAmount4 
from(
select Plan.Id PlanId,LockAmountTable.LockAmount,LockAmountTable.NumForecast 
from PlanTable

left join LockAmountTable on
LockAmount.IdPlan = rpo.Id
)p
PIVOT
(
SUM (LockAmount)
FOR NumForecast IN
( [1][1],[2],[3],[4])
) AS pvt2)
select * from pivot_1 p1 
inner join pivot_2 p2 on p1.pvt1PlanID=p2.pvt2PlanID