执行到没有列的临时表中,因为它们是动态的

时间:2018-12-13 05:34:35

标签: sql-server

我正在研究枢轴功能,其中枢轴列是动态产生的。我需要计数的所有枢轴列,并在枢轴选择语句本身中显示单独的列。

SELECT CurriculumSegment,attendancedate,section,Class,count(*) as 
TotalWorkingDays into #NewTempWithTotalDaysCount
   FROM  #temp1 group by CurriculumSegment,attendancedate,Section,Class 
   order by  CurriculumSegment, attendancedate,Class,Section

SELECT CurriculumSegment,attendancedate,section,Class,count(*) as 
CountOfPresentDays into #NewTempWithTotalPresentDaysCount
   FROM  #temp1 where attendance='P' group by 
 CurriculumSegment,attendancedate,Section,Class order by CurriculumSegment, 
attendancedate,Class,Section


select a.AttendanceDate,a.Class,a.CurriculumSegment,
a.Section,a.TotalWorkingDays,b.CountOfPresentDays,(a.TotalWorkingDays - 
b.CountOfPresentDays) as TotalAbsentDays, (b.CountOfPresentDays * 
 100)/a.TotalWorkingDays as PercentOfPresentDays
into #TempWithTotalDaysCount 
from #NewTempWithTotalDaysCount a left outer join 
#NewTempWithTotalPresentDaysCount b 
on a.AttendanceDate =b.AttendanceDate and a.CurriculumSegment = 
 b.CurriculumSegment and a.Section= b.Section and a.Class = b.Class

-- Query 1
select  sum(TotalWorkingDays) as TotalCount,sum(TotalAbsentDays) as 
AbsentCount,sum(CountOfPresentDays) as 
PresentCount,curriculumsegment,section,class 
from #TempWithTotalDaysCount group by class,curriculumsegment,section

SET @query = 'SELECT [CurriculumSegment],Class,section,'+@cols+'
FROM ( 
SELECT [CurriculumSegment],
Class,section,PercentOfPresentDays,AttendanceDate  FROM 
#TempWithTotalDaysCount) AS up 
PIVOT (MAX(PercentOfPresentDays) FOR AttendanceDate IN ('+@cols+')) AS pvt' 

-- Query 2
EXEC (@query) 

从查询1和查询2的结果中,我需要加入并获取TotalCount,AbsentCount,PresentCount 在查询2的结果中。

是否可以在临时表中放入“ EXEC(@query)”? 我尝试过,但是我得到的对象无效。因为当列名动态变化时,我无法给出它们的名称,所以它们会形成数据透视。 那么,还有其他方法吗?

谢谢。

在下图中找到我的结果: enter image description here

0 个答案:

没有答案