将行转换为报表的列

时间:2015-05-05 13:44:18

标签: sql access-vba ms-access-2013

使用找到的说明here我尝试创建交叉表查询以显示前三年的历史数据,我想将其输出到报告中。

我遇到了一些令人困难的并发症,我无法正确显示数据。

它所基于的查询结构如下:

EmpID | ReviewYearID | YearName | ReviewDate  | SelfRating | ManagerRating | NotSelfRating |
  1   |      5       |   2013   | 01/09/2013  |    3.5     |      3.5      |      3.5      |
  1   |      6       |   2014   | 01/09/2014  |    2.5     |      2.5      |      2.5      |
  1   |      7       |   2015   | 01/09/2015  |    4.5     |      4.5      |      4.5      |
  2   |      6       |   2014   | 01/09/2014  |    2.0     |      2.0      |      2.0      |
  2   |      7       |   2015   | 01/09/2015  |    2.0     |      2.0      |      2.0      |
  3   |      7       |   2015   | 01/09/2015  |    5.0     |      5.0      |      5.0      |

[编辑]:这是基本查询的SQL。它结合了两个表中的数据:

SELECT tblEmployeeYear.EmployeeID AS EmpID, tblReviewYear.ID AS ReviewYearID, tblReviewYear.YearName, tblReviewYear.ReviewDate, tblEmployeeYear.SelfRating, tblEmployeeYear.ManagerRating, tblEmployeeYear.NotSelfRating
FROM tblReviewYear INNER JOIN tblEmployeeYear ON tblReviewYear.ID = tblEmployeeYear.ReviewYearID;

[/编辑]

我希望交叉表查询转置列/行,以显示特定员工最多3年前的历史数据(基于审核日期)。对于员工ID 1,最终结果看起来像这样:

Year          |  2015  |  2014  |  2013  |
SelfRating    |  4.5   |  2.5   |  3.5   |
ManagerRating |  4.5   |  2.5   |  3.5   |
NotSelfRating |  4.5   |  2.5   |  3.5   |

其他员工的列数较少,因为他们没有前几年的数据。

我遇到了将其过滤到特定员工并按其审核日期对年份进行排序的问题(名称并不总是对其进行排序的可靠方式)。

最后,我希望将此作为报告的数据。

如果有一个不同于交叉表查询的方式来实现这一点,我也可以这样做。

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要所有评级类型的列,而不是每种类型的单个列。如果您无法重新设计表格,我建议您为自己的目的创建一个新表格。下面使用union来添加上面提到的那个类型列。您创建一个列并对该值进行硬编码(SelfRating,ManagerRating等):

SELECT * INTO EmployeeRatings
FROM (SELECT tblEmployeeYear.EmployeeId AS EmpId, ReviewYearId, "SelfRating" AS Category, SelfRating AS Score
      FROM tblEmployeeYear
      WHERE SelfRating Is Not Null
      UNION ALL
      SELECT tblEmployeeYear.EmployeeId, ReviewYearId, "ManagerRating", ManagerRating
      FROM tblEmployeeYear
      WHERE ManagerRating Is Not Null
      UNION ALL
      SELECT tblEmployeeYear.EmployeeId, ReviewYearId, "NotSelfRating", NotSelfRating
      FROM tblEmployeeYear
      WHERE NotSelfRating Is Not Null)

然后使用新创建的表代替tblEmployeeYear。请注意,我使用的Year([ReviewDate])只返回年份。此外,由于看起来每年可能有多个审核类型,我平均每年的Score

TRANSFORM Avg(Score)
SELECT EmpId, Category
FROM (SELECT EmpId, Category, ReviewDate, Score
      FROM tblReviewYear 
      INNER JOIN EmployeeRatings
              ON tblReviewYear.ID = EmployeeRatings.ReviewYearID) AS Reviews
GROUP BY EmpId, Category
PIVOT Year([ReviewDate]);