简体   繁体   English

MS Access 将查询结果行透视到列中

[英]MS Access Pivoting Query Result Rows into Columns

I'm new to working with MS-Access reports.我是使用 MS-Access 报告的新手。 I have a query that returns the results of employees timesheets, grouped by both month and paycode.我有一个查询返回员工时间表的结果,按月份和工资码分组。 I'd like to make a report showing the the following我想做一份报告,显示以下内容

Employee员工 OT Shifts Jan加班班一月 Regular Shifts Jan定期轮班 OT Shifts Feb加班班二月 Regular Shifts Feb定期轮班二月
1234 1234 1 1 1 1 2 2 1 1
5678 5678 5 5 2 2 1 1 0 0

However my query is formatted as:但是我的查询格式为:

Employee员工 Month Shift转移 Paycode支付码
1234 1234 Jan 1 1 OT旧约
1234 1234 Jan 1 1 Regular常规的
1234 1234 Feb二月 2 2 OT旧约
1234 1234 Feb二月 1 1 Regular常规的
5678 5678 Jan 5 5 OT旧约
5678 5678 Jan 2 2 Regular常规的
5678 5678 Feb二月 1 1 OT旧约
5678 5678 Feb二月 0 0 Regular常规的

Can a field on a report be conditionally told to reference a specific "Where clause" so that I can move the fields around at will or do I need to reform my query to be able to do this?是否可以有条件地告诉报告中的字段引用特定的“Where 子句”,以便我可以随意移动字段,或者我是否需要修改我的查询才能做到这一点?

For reference my Query code is:作为参考,我的查询代码是:

SELECT tblAssignedEmployees.EmployeeID, Format(Date_In,"yyyy-mm") AS [Month], Count(tblShift.Date_In) AS ShiftsPerEmployee, tblAssignedEmployees.PayCode
FROM tblShift INNER JOIN tblAssignedEmployees ON tblShift.ShiftNum = tblAssignedEmployees.ShiftNum
GROUP BY tblAssignedEmployees.EmployeeID, Format(Date_In,"yyyy-mm"), tblAssignedEmployees.PayCode;

Consider conditional aggregation:考虑条件聚合:

SELECT e.EmployeeID
     , SUM(IIF(MONTH(s.Date_In) = 1 AND e.PayCode = 'OT', 1, 0) AS [OT Shifts Jan]
     , SUM(IIF(MONTH(s.Date_In) = 1 AND e.PayCode = 'Regular', 1, 0) AS [Regular Shifts Jan]
     , SUM(IIF(MONTH(s.Date_In) = 2 AND e.PayCode = 'OT', 1, 0) AS [OT Shifts Feb]
     , SUM(IIF(MONTH(s.Date_In) = 2 AND e.PayCode = 'Regular', 1, 0) AS [Regular Shifts Feb]
FROM tblShift s
INNER JOIN tblAssignedEmployees e
   ON s.ShiftNum = e.ShiftNum
GROUP BY e.EmployeeID

Even shorter without IIF , sum the True conditions but multiply by -1 since Access treats True as -1 and False as 0.没有IIF甚至更短,将 True 条件相加但乘以 -1,因为 Access 将 True 视为 -1, False 视为 0。

SELECT e.EmployeeID
     , SUM(MONTH(s.Date_In) = 1 AND e.PayCode = 'OT') * -1 AS [OT Shifts Jan]
     , SUM(MONTH(s.Date_In) = 1 AND e.PayCode = 'Regular') * -1 AS [Regular Shifts Jan]
     , SUM(MONTH(s.Date_In) = 2 AND e.PayCode = 'OT') * -1 AS [OT Shifts Feb]
     , SUM(MONTH(s.Date_In) = 2 AND e.PayCode = 'Regular') * -1 AS [Regular Shifts Feb]
FROM tblShift s
INNER JOIN tblAssignedEmployees e
   ON s.ShiftNum = e.ShiftNum
GROUP BY e.EmployeeID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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