SQL将多个列拆分为多个行

时间:2012-05-02 14:37:53

标签: sql sql-server-2008

我遇到这个问题很困难。

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

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

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

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

这可以执行吗?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

你可以使用UNPIVOT。

SELECT p.OrderID, p.Employee
FROM (SELECT OrderID, Manager, Worker FROM table) a
UNPIVOT (Employee FOR FieldName IN (Manager, Worker)) p

答案 2 :(得分:0)

尝试类似

的内容
SELECT OrderID, Manager AS Employee, 'Manager' AS EmployeeRole From Employess
UNION ALL
SELECT OrderID, Worker AS Employee, 'Worker' AS EmployeeRole From Employess