我有以下查询为学生生成经济援助奖励表。我们想做一个Pivot,因为我们想要同时展示多个学期的辅助。
select pt.award as Award, pt.[1] as Fall, pt.[2] as Spring, pt.[3] as Summer
--into #awardTemp
from (select fa.Description as award, fa.OriginalAmount, fa.TextTerm,
ROW_NUMBER() OVER(PARTITION BY fa.description
order by fa.textterm) AS M
from CAMS_Enterprise.dbo.cams_FinancialAward_view as fa
where fa.Code1ID = 0
and fa.StudentAccepted is null
and fa.studentuid = @studentuid) as AT
pivot (max(at.originalamount) for at.m in ([1],[2],[3])) as pt
我们得到的结果如下所示,而不是在同一行上列出每学期的金额。尽管描述标题相同,但每个学期的奖项都有自己的一行。有谁知道问题来自哪里?
Academic Scholarship 5000.00 NULL NULL
Academic Scholarship NULL 5000.00 NULL
Federal Subsidized Stafford Loan 1750.00 NULL NULL
Federal Subsidized Stafford Loan NULL 1750.00 NULL
Federal Unsubsidized Stafford Loan 1000.00 NULL NULL
Federal Unsubsidized Stafford Loan NULL 1000.00 NULL
答案 0 :(得分:3)
如果没有在pivot
之前查看表格中的数据,我猜测这是因为查询中包含fa.TextTerm
。
这会给出导致多行的TextTerm
的明确值。
这似乎是问题的明显原因,因为您没有在最终的SELECT
列表中使用该列。我建议将您的查询更改为:
select pt.award as Award, pt.[1] as Fall, pt.[2] as Spring, pt.[3] as Summer
--into #awardTemp
from
(
select fa.Description as award,
fa.OriginalAmount,
ROW_NUMBER() OVER(PARTITION BY fa.description order by fa.textterm) AS M
from CAMS_Enterprise.dbo.cams_FinancialAward_view as fa
where fa.Code1ID = 0
and fa.StudentAccepted is null
and fa.studentuid = @studentuid
) as AT
pivot
(
max(at.originalamount)
for at.m in ([1],[2],[3])
) as pt