SQL将字符串作为值进行透视

时间:2015-07-08 13:45:12

标签: sql sql-server pivot

我有一个基于日期范围的动态查询,需要列出所有用户假日,其日期范围显示为列标题。有许多假日类型(tblHolidayType)1到7.当我根据数字(类型)转动表时,数据透视表正常运行。但是,当我尝试将假日类型显示为字母时,查询会为同一用户返回多行。

我尝试过rownumber但似乎没有用。

declare @cols as nvarchar(max),
        @query as nvarchar(max),
        @hDateS date,
        @hDateF date,
        @hYear nvarchar(4),
@hQuarter int

set @hQuarter = 1
set @hYear = '2015'

select @hDateS =  case @hQuarter
when 1 then  cast(@hYear +'-01-01' as date)
when 2 then cast(@hYear +'-04-01' as date)
when 3 then cast(@hYear +'-07-01' as date)
when 4 then  cast(@hYear +'-10-01' as date)
end


select @hDateF =  case @hQuarter
when 1 then  cast(@hYear +'-03-31' as date)
when 2 then cast(@hYear +'-06-30' as date)
when 3 then cast(@hYear +'-09-30' as date)
when 4 then  cast(@hYear +'-12-31' as date)
end


select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(CHAR(10), Dates, 120)) 
                    from tblDateRange where dates between (select case datepart(dw,@hDateS) when  2 then @hDateS else cast(CAST(@hDateS as datetime) -(datepart(dw,@hDateS) - 2) as date) end) and @hDateF
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') 




set @query = 'SELECT UserID,Name, ' +@cols + '
FROM (
    select  d.Dates,h.UserID,h.Type,u.Name,ht.Init, row_number() over(partition by ht.iD order by ht.Init) rn from tblDateRange d left outer join
(select * from tblHoliday) h on d.Dates = h.HolidayDate left outer join
(select * from tblUser) u on h.UserID = u.UserID left outer join
(Select * from tblHolidayType) ht on h.Type = ht.ID
where u.active = 1 and u.userid = 13
) as s
PIVOT
(
    max(Init)
    FOR Dates in (' + @cols + ')
    ) P'


execute(@query) 

以下是select语句和数据透视的输出。

enter image description here

enter image description here

0 个答案:

没有答案