1

我在 SQL Server (SSMS) 中使用三个像这样的表

表 A

ProcessID Step Approver  
  17       10    Kim  
  18       20    Joe  
  19       10    Beth  
  20       20    Josh  

表 B

ProcessID DeptCode  
   17       515  
   18       515  
   19       190  
   20       190  

表 C

ProcessID AlternateApprover  
   17        Sarah  
   18        David  
   19        Don  
   20        Don

并希望我的结果格式为:

DeptCode FirstApprover FirstAlternate SecondApprover SecondAlternate  
   515       Kim           Sarah          Joe             David  
   190       Beth          Don            Josh            Don

我已经成功地管理了仅批准者的支点,但不确定如何加入替代者(表 C)。

我知道这种规范化有点奇怪 - 它不是我的数据库,我无法控制表结构

4

1 回答 1

2

这是旋转多列的更简单方法。

;WITH cte AS 
(
    SELECT  [DeptCode],
            [Approver],
            '' AS [Alternate],
            ROW_NUMBER() OVER (PARTITION BY DeptCode ORDER BY b.ProcessID) Rn
    FROM    TableB b
            JOIN TableA a ON a.ProcessID = b.ProcessID
    UNION ALL
    SELECT  [DeptCode],
            '',
            AlternateApprover,
            ROW_NUMBER() OVER (PARTITION BY DeptCode ORDER BY b.ProcessID) Rn
    FROM    TableB b
            JOIN TableC a ON a.ProcessID = b.ProcessID
)
SELECT  [DeptCode],
        MAX(CASE WHEN Rn = 1 THEN [Approver] END) AS FirstApprover,
        MAX(CASE WHEN Rn = 1 THEN [Alternate] END) AS FirstAlternate,
        MAX(CASE WHEN Rn = 2 THEN [Approver] END) AS SecondApprover,
        MAX(CASE WHEN Rn = 2 THEN [Alternate] END) AS SecondAlternate
FROM    cte
GROUP BY [DeptCode]

这假设 First 和 Second order 由 ProcessID 确定,ROW_NUMBER() OVER (PARTITION BY DeptCode ORDER BY b.ProcessID)因为您在 TableA 中有 Step 但没有 TableC 我不确定该字段代表什么。

于 2016-06-22T18:45:59.477 回答