简体   繁体   中英

PIVOT / crosstab table by month SQL Server 2005

I have the following query

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

That results on the following result

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

but I need the result to be shown in this format

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

Do you guys know how I can achieve this?

Thanks on anticipation

Try the query below if you want to do it on the server side.

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

Change the month names accordingly.

Here is a dynamic way using a Crosstab:

SAMPLE DATA

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');

SOLUTION

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM