1

我有一个表来存储员工出勤率,其中包含以下列:

  • 编号:int,pk
  • 员工姓名:varchar
  • 公司名称:varchar
  • isPresent: varchar
  • 日期:日期时间

如何编写一个给出一个月出勤率的查询?

例如:为 XYZ 公司生成 4 月份的报告,它应该看起来像

StaffName       1 2 3 4 5 6 7 8 9....up to last day of month
--------------------------------------------------------------
John lenon      p p p a p a a p a....
Bob Dylan       a a a p p p p p a....
Keith Moon      p p p p a p a p p....
4

2 回答 2

0

您可以使用PIVOT功能将日期作为列旋转(这里是一个快速而肮脏的示例,您可以检查日期格式和顺序):

SELECT StaffName, [0], [1], [2], [3], [4] and so on...
FROM
(SELECT StaffName, isPresent, date FROM myTable) AS SourceTable
PIVOT
(
MAX(isPresent)
FOR date IN ([0], [1], [2], [3], [4] and so on...)
) AS PivotTable;
于 2013-05-31T09:05:03.543 回答
0

对于 qynamic 查询,这可能有点棘手。对于表:

CREATE TABLE [dbo].[attendance](
    [id] [int] NOT NULL,
    [StaffName] [varchar](100) NULL,
    [CompanyName] [varchar](100) NULL,
    [isPresent] [char](1) NULL,
    [date] [datetime] NULL,
    PRIMARY KEY CLUSTERED  ( [id] ASC )
)
go 

以下脚本生成以天为列的“枢轴兼容”脚本

--report params
DECLARE @month int, @year int, @lastDay int
set @month = 1 
set @year = 2012


-- calculations
DECLARE @startDate datetime, @endDate datetime
SET @startDate =  convert(varchar, @year) + '-' + convert(varchar, @month) + '-1'
set @endDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startDate)+1,0))
set @lastDay =  day(@endDate) --last day of month

print('showing data from ' + convert(varchar, @startDate) + ' to ' + convert(varchar, @endDate))
print('original report')
SELECT StaffName, isPresent, day([date]) as day FROM attendance
where [date] between @startDate and @endDate

declare @day int
set @day = 2


declare @days varchar(max)
set @days = '[1]'
WHILE (@day <= @lastDay)
BEGIN
   set @days = @days + ',[' + convert(varchar, @day) + ']'
   set @day = @day + 1
END

-- select @days

declare @query varchar(max)

set @query = '
SELECT StaffName, ' + @days  +
'
FROM
(SELECT StaffName, isPresent, day(date) as day FROM attendance) AS SourceTable
PIVOT
(
MAX(isPresent)
FOR day IN ( ' + @days + ')' + '
) AS PivotTable;'

--select @query

print('pivoted report')    
exec(@query)
于 2013-05-31T09:45:37.377 回答