这就是可用数据(表名:tblAttendanceD)的方式
EmployeeNo | Type | StartDate | EndDate
M1975012200006 | TRAVEL | 06/03/2013 | 06/03/2013
M1975040500009 | TRAVEL | 06/17/2013 | 06/17/2013
M1975012200006 | WORK | 06/04/2013 | 07/15/2013
M1975040500009 | WORK | 06/18/2013 | 09/01/2013
M1975012200006 | LEAVE | 07/17/2013 | 09/01/2013
M1975040500009 | LEAVE | 09/03/2013 | 10/15/2013
--declare temporary table to store example data
DECLARE @tblAttendanceD TABLE (EmployeeName VARCHAR(30),
EmployeeNo VARCHAR(30),
[AttendanceType VARCHAR(30), Start_Date DATETIME, End_Date DATETIME)
--insert data into temporary table
INSERT INTO @tblAttendanceD (EmployeeName, EmployeeNo, [Type] , StartDate, EndDate)
SELECT 'Dumitru', 'M1975012200006', 'TRAVEL', '06/03/2013', '06/03/2013'
UNION ALL SELECT 'Mottaghi', 'M1975040500009', 'TRAVEL', '06/17/2013',
'06/17/2013'
UNION ALL SELECT 'Alvarado', 'M1986092400012', 'TRAVEL', '06/03/2013',
'06/03/2013'
UNION ALL SELECT 'Mottaghi', 'M1975040500009', 'WORK', '06/18/2013', '09/01/2013'
UNION ALL SELECT 'Alvarado', 'M1986092400012', 'WORK', '06/04/2013', '07/15/2013'
UNION ALL SELECT 'Mottaghi', 'M1975040500009', 'LEAVE', '09/03/2013', '10/15/2013'
UNION ALL SELECT 'Alvarado', 'M1986092400012', 'LEAVE', '07/17/2013', '09/01/2013'
我想明智地显示一个月中的所有日子。
预期输出如下
六月时间表
员工人数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 M1975012200006
- T - 代表旅行天数;
- W——代表工作日;
- L - 代表 LEAVE 天数;
2013 年 7 月 25 日更新
我能够获取如下所示的记录。对于表中的那些日期,我可以填写相应的“类型”。
但“类型”也应根据开始日期和结束日期复制到下一个日期。
员工人数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 M1975012200006 TW - - - - - - - - - - - TL - - - - - - - - - - - - - - - - - - - - Employee Numb2 - - - - - - - - - - - - - - - - TL - - - -....等。
这是脚本:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
DECLARE @Days TABLE (DateField DATETIME)
DECLARE @CurrentDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @mydate DATETIME
SET @mydate = GetDate();
SELECT @CurrentDate = DATEADD(dd,-(DAY(@mydate)-1),@mydate)
SELECT @EndDate =DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate))
WHILE @CurrentDate <= @EndDate
BEGIN
INSERT INTO @Days VALUES(@CurrentDate)
SET @CurrentDate = DateAdd(d,1,@CurrentDate)
End
SELECT @cols = STUFF((SELECT '],[' +
CAST(DAY(DateField) As varchar(10))
FROM @Days
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
--select @cols;
SELECT @query =
'SELECT *
FROM
(
SELECT EmployeeNo, AttendanceType, Day([StartDate]) As [Start_Date] FROM @tblAttendanceD WHERE ISNULL(Deleted,0)=0
) AS t
PIVOT
(
MAX([AttendanceType]
)
FOR [Start_Date] IN( ' + RIGHT(@cols, LEN(@cols) - 1) + '] )' +
' ) AS p ; ';
print @query;
execute(@query);