5

我在这个问题上遇到了困难。

我有一个具有这种结构的表:

OrderID | Manager   | Worker      
1       | John      | Sally       
2       | Tim       | Kristy       

我需要一个 SQL 查询来获得这样的结果集:

OrderID | Employee       
1       | John           
1       | Sally    
2       | Tim 
2       | Kristy

这可以执行吗?

4

3 回答 3

6

我能想到的最简单的方法是(假设您不在乎 Tim 是在 Kristy 之前还是之后列出的):

SELECT OrderID, Employee = Manager FROM dbo.table
UNION ALL
SELECT OrderID, Employee = Worker FROM dbo.table
ORDER BY OrderID;

如果订单很重要,并且您总是首先需要经理,那么:

SELECT OrderID, Employee FROM
(
  SELECT r = 1, OrderID, Employee = Manager
  FROM dbo.Table
  UNION ALL
  SELECT r = 2, OrderID, Employee = Worker
  FROM dbo.table
) AS x
ORDER BY OrderID, r;
于 2012-05-02T14:40:59.170 回答
4

您可以为此使用 UNPIVOT。

SELECT p.OrderID, p.Employee
FROM (SELECT OrderID, Manager, Worker FROM table) a
UNPIVOT (Employee FOR FieldName IN (Manager, Worker)) p
于 2012-05-02T14:43:13.660 回答
0

尝试类似的东西

SELECT OrderID, Manager AS Employee, 'Manager' AS EmployeeRole From Employess
UNION ALL
SELECT OrderID, Worker AS Employee, 'Worker' AS EmployeeRole From Employess
于 2012-05-02T14:42:50.227 回答