PIVOT /交叉表逐月SQL Server 2005

时间:2014-11-28 00:20:49

标签: sql sql-server

我有以下查询

SELECT
     DATENAME(year,BBIT_Fecha) as [Year] 
    ,DATENAME(month,BBIT_Fecha) as [Month]
    ,isnull(BBIT_Estatus,'Pendiente') as [Status]
FROM 
    [BitacoraTrabajo].[dbo].[B_Bitacora]
WHERE 
    BUSU_IdUsuario = 1416127
ORDER BY
    BBIT_Fecha

这导致以下结果

    year                            Month                            Status
------------------------------ ------------------------------ --------------------
2014                           April                             Pendent
2014                           September                         Pendent
2014                           October                           Pendent
2014                           November                          Saved

但我需要以这种格式显示结果

year      April      September      October          November   
------ ----------- ------------- --------------- --------------- 
2014    Pendent       Pendent       Pendent           Saved

你们知道我怎么能做到这一点吗?

感谢您的期待

2 个答案:

答案 0 :(得分:1)

如果您想在服务器端执行此操作,请尝试以下查询。

select *
from
(
select year, month, status -- your query here instead. don't use order by.
FROM [B_Bitacora]
) as src
pivot
(
max(status) for month in ([apr],[sep],[oct],[nov]) 
) as pvt

相应地更改月份名称。

答案 1 :(得分:0)

以下是使用交叉表的动态方式:

示例数据

create table BitacoraTrabajo(
    BUSU_IdUsuario int,
    BBIT_Fecha date,
    BBIT_Estatus varchar(10)
)
insert into BitacoraTrabajo values
(1416127 ,'20140401' ,'Pendent'), (1416127 ,'20141001' ,'Pendent'), 
(1416127 ,'20140901' ,'Pendent'), (1416127 ,'20141101' ,'Saved');

declare @sql1 varchar(4000) = ''
declare @sql2 varchar(4000) = ''
declare @sql3 varchar(4000) = ''

select @sql1 =
'select
    datename(year, BBIT_Fecha) as year
'

select @sql2 = @sql2 + 
'   ,max(case when datename(month, BBIT_Fecha) = ''' + [month] + ''' then [BBIT_Estatus] end) ' +  'as [' + [month] + ']' + char(10)
from(
    select distinct 
        datename(month, BBIT_Fecha) as [month], 
        datepart(mm, BBIT_Fecha) as m
    from BitacoraTrabajo
    where BUSU_IdUsuario = 1416127    
)t
order by m

select @sql3 =
'from BitacoraTrabajo
where BUSU_IdUsuario = 1416127
group by datename(year, BBIT_Fecha)'

print (@sql1 + @sql2 + @sql3)
exec (@sql1 + @sql2 + @sql3)