【发布时间】:2015-02-15 02:20:56
【问题描述】:
我是 SQL Server 的初学者,正在努力弄清楚如何更新我的查询,以便正确显示我的数据。
我查看了Combine similar column data from two rows into one row 并尝试在 QueryID 上进行分组,但是当我需要它按文本末尾的数字和 id# 分组时,我不确定如何应用它。我还查看了许多关于枢轴/取消枢轴以执行多个枢轴的帖子,但我正在努力应用它。
我当前的查询和示例结果如下。我想看到的是 QueryID 以相同的数字结尾并且员工 ID 相等,日期/级别/原因都返回到同一行而不是 3 个单独的行。我感谢任何指导。
With DisciplineTable as
(
Select HrEmployees.Number,
HrEmployees.FirstName + ' ' + HrEmployees.LastName as Name,
HrEmployeeQueries.QueryID,
HrEmployeeQueries.Query,
HrEmployeeQueries.Response
From HrEmployeeQueries
Left Join HrEmployees on HrEmployees.EmployeeID = HrEmployeeQueries.EmployeeID
Where QueryID Like 'DIS%')
Select *
From DisciplineTable
Pivot(Max(Response) for Query in ([DATE:],[LEVEL:],[REASON:])) as DisciplinaryAction
Where QueryID Like 'DIS%'
Order by Name
我的结果如下所示:
+-----+----------+---------+----------+---------+-------------+
| # | Name | QueryID | DATE: | LEVEL: | REASON: |
+-----+----------+---------+----------+---------+-------------+
| 123 | John Doe | Date2 | 10/16/14 | Null | Null |
| 123 | John Doe | Level2 | Null | Serious | Null |
| 123 | John Doe | Reason2 | Null | Null | Attendance |
| 123 | John Doe | Date3 | 12/13/14 | Null | Null |
| 123 | John Doe | Level3 | Null | Major | Null |
| 123 | John Doe | Reason3 | Null | Null | Performance |
+-----+----------+---------+----------+---------+-------------+
我正试图让它们看起来像这样。 Action 列应填充 QueryID 末尾的数值,该数值可以从 1 到 10。 QueryID 开头的文本将始终为 Date、Reason 或 Level:
+-----+----------+--------+----------+---------+-------------+
| # | Name | Action | DATE: | LEVEL: | REASON: |
+-----+----------+--------+----------+---------+-------------+
| 123 | John Doe | 2 | 10/16/14 | Serious | Attendance |
| 123 | John Doe | 3 | 12/13/14 | Major | Performance |
+-----+----------+--------+----------+---------+-------------+
【问题讨论】:
-
CTE内部查询的输出是什么
-
什么是
Action?看起来您需要从子查询中删除QueryID列并将其替换为Action列。 -
@bluefeet Action 只是 QueryID 末尾的数字 - 所以 Date2、Level2 和 Reason 2 将在 Action 列中显示为 2。
-
@HRIS 操作是否只有一个数值,例如
2或3?或者你会有10,100? -
@NoDisplayName - 枢轴之前的 DisciplineTable 结果基本上是这样的:123 |约翰·多伊 |日期2 |日期:| 2014 年 10 月 16 日,因此枢轴将 DATE、LEVEL 和 REASON 作为列标题向上移动到其“响应”之上。
标签: sql-server tsql pivot