将报表的行转换为列

Convert rows to columns for a Report

使用找到的说明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;

[/编辑]

我想要一个转换 columns/rows 的交叉表查询,以显示特定员工最多 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   |

其他员工的列会更少,因为他们没有往年的数据。

我在将其筛选到特定员工并按审查日期对年份进行排序时遇到问题(名称并不总是一种可靠的排序方式)。

最后我希望将其用作报告的数据。

如果有不同于交叉表查询的方法来完成此操作,我也可以接受。

谢谢!

您需要为所有评级类型创建一个列,而不是为每个类型单独创建一个列。如果您不能重新设计 table,我建议您创建一个新的。下面使用联合添加到上面提到的那个类型列中。您创建一个列并对值(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)

然后使用新创建的 table 代替 tblEmployeeYear。请注意,我使用的 Year([ReviewDate]) 只会 return 年份。此外,由于看起来每年每种评论类型可能有不止一种,因此我对这一年的 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]);