数据透视表不起作用

时间:2013-12-02 13:47:39

标签: sql-server

DECLARE @temp AS TABLE(dates datetime)

;with cte (datelist, maxdate) as
(
    select DATEADD(dd,-3,GETDATE()), GETDATE()
    union all
    select dateadd(dd, 1, datelist), maxdate
    from cte
    where datelist < maxdate
)
INSERT INTO @temp
SELECT c.datelist
FROM cte c 


DECLARE @listdate nvarchar(MAX)  


SELECT @listdate = (select(STUFF( (SELECT ', ' + QUOTENAME(convert(CHAR(10), dates, 120))                        
    from @temp ORDER BY dates asc                       
    FOR XML PATH('')),1, 1, '')))    

print @listdate


exec('with data as (SELECT * from
(select distinct sf_fname + '' '' + sf_lname as Teacher,ay_title AS Activity,at_id as attendance,
        QUOTENAME(convert(CHAR(10), at_date, 120)) AS DATES from
        mts_sos_hours sos inner join mts_staff on
        sos_teacherid = sf_id
        inner join mts_activity on ay_id = sos_activity
        inner join mts_attendance on at_activityid = ay_id           
        group by sf_fname + '' '' + sf_lname,ay_title,at_id,
        QUOTENAME(convert(CHAR(10), at_date, 120))
) p            
PIVOT            
(            
COUNT (attendance)            
FOR DATES IN ('+@listdate+')) AS pvt            
)            
select * from data 
')         

我已将此链接用作参考https://dba.stackexchange.com/questions/25809/sql-query-to-return-a-column-per-date-in-date-range。我正在创建的上述查询在计算后只检索0值,任何人都可以告诉我我在做什么错。

0 个答案:

没有答案