2

我的 HR 项目有一张带有字段的表格:

EmpName(nvarchar(50)),LeaveType(nvarchar(10)),FromDate(datetime),ToDate(datetime)

和下面的示例数据输入:

EmpName LeaveType  FromDate     ToDate
AA         AL      22-May-13    28-May-13
BB         SPL     25-May-13    31-May-13

在报告中,我想每天选择数据,如下所示:

EmpName 22-May-13   23-May-13   24-May-13   25-May-13   26-May-13   27-May-13   28-May-13   29-May-13   30-May-13   31-May-13
AA         AL         AL          AL          AL          AL          AL    AL          
BB                                             SPL        SPL          SPL       SPL     SPL     SPL               SPL

如何通过 sql server 2008 R2 中的存储过程完成此报告?非常感谢您的帮助。谢谢!

4

2 回答 2

2

试试这个 :

Declare @Emp table 
(EmpName varchar(10), LeaveType varchar(10),
 FromDate  date,ToDate date)

insert into @Emp values('AA','AL','22-May-13','28-May-13')
insert into @Emp values('BB','SPL','25-May-13','31-May-13')

select * from @emp

;with cte as
(select EmpName,LeaveType, FromDate ,ToDate from @Emp
union all

select EmpName,LeaveType,DATEADD(dd,1,FromDate),ToDate
 from cte where FromDate<ToDate)

select * into #demo from
(select EmpName,LeaveType,FromDate from cte ) a



Declare @col varchar(2000)
select @col=STUFF(
(select ',[' + cast(FromDate as varchar) + ']' from 
    (select distinct FromDate from #demo)b For XML path('')),
1,1,'')


print @col

Declare @query varchar(max)
SET @query =
    'SELECT EmpName, ' + @col + '
     FROM (SELECT EmpName, LeaveType, FromDate 
          FROM #demo ) a
     PIVOT (
            MIN([LeaveType])
            FOR FromDate IN (' + @col + ')
            ) AS pvt
    ORDER BY pvt.EmpName'


exec (@query)


drop table #demo
于 2013-05-22T05:26:08.020 回答
1

该解决方案基于Dynamic PIVOT

use tempdb
go

if OBJECT_ID('tempdb..#tbl') is not null
    drop table #tbl
if OBJECT_ID('tempdb..#date') is not null
    drop table #date
if OBJECT_ID('tempdb..#ForPivot') is not null
    drop table #ForPivot

create table #tbl (EmpName varchar(100),LeaveType varchar(2), DateFrom date, DateTo date) 

insert into #tbl values ('Tom','TH','20130516','20130527'), ('Hucklberry','LT','20130507','20130520')

create table #Date (d date)

declare @d date='20130101'
WHILE @d<'20140101'
    BEGIN
        INSERT INTO #Date values(@d)
        set @d=dateadd(DAY,1,@d)
    END

SELECT t.EmpName, t.LeaveType, convert(varchar(10),d,120) d
INTO #ForPivot
FROM #tbl t
    cross join #Date d
WHERE d.d BETWEEN t.DateFrom AND t.DateTo


declare @sql varchar(max)
declare @select_list varchar(max)

select @select_list=ISNULL(@select_list+',','')+'['+d+']' from #ForPivot group by d order by d


    SET @sql =
    'SELECT EmpName, ' + @select_list + '
     FROM (SELECT EmpName, LeaveType, d 
          FROM #ForPivot TS) TS
     PIVOT (
            MIN([LeaveType])
            FOR d IN (' + @select_list + ')
            ) AS pvt
    ORDER BY pvt.EmpName
    '
--select @sql
--select @select_list
--select * from #ForPivot

exec (@sql)
于 2013-05-22T04:54:01.487 回答