查询表以便合并结果并按行返回

时间:2011-11-08 16:00:33

标签: sql sql-server sql-server-2005 tsql

我需要为报告提取数据,以便列式数据现在是行数据:

empID  planID  coverage
-----  ------  --------
15     1       100
15     11      200
15     12      NULL    
15     13      500
20     1       100
20     11      250
20     12      400
20     13      NULL

变为:

emp  Basic  Supplemental  Spouse  Dependent
---  -----  ------------  ------  ---------
15   100    200                   500
20   100    250           400  

我尝试了各种JOINS和最佳案例scenerio获得4倍的结果数量,因为它重复了前一个表中的每一行。

SELECT DISTINCT 
CASE benefitSelected.planID WHEN 1 THEN benefitSelected.coverageLev END AS Basic, 
CASE benefitSelected_1.planID WHEN 11 THEN benefitSelected_1.coverageLev END AS Supplemental,
CASE benefitSelected_2.planID WHEN 12 THEN benefitSelected_2.coverageLev END AS Spouse,
CASE benefitSelected_3.planID WHEN 13 THEN benefitSelected_3.coverageLev END AS Dependent
FROM benefitSelected AS benefitSelected_3
  FULL OUTER JOIN benefitSelected AS benefitSelected_2 ON benefitSelected_3.empID = benefitSelected_2.empID
  FULL OUTER JOIN benefitSelected AS benefitSelected_1 ON benefitSelected_2.empID = benefitSelected_1.empID
  FULL OUTER JOIN benefitSelected
    RIGHT OUTER JOIN employee ON benefitSelected.empID = employee.empID
  ON benefitSelected_1.empID = benefitSelected.empID 

我做错了什么,如何得到我想要的结果?

感谢您的关注!

编辑: PIVOT查询结果如下

--  --------  ---------  ----  --------
1   10000.00  NULL       NULL  NULL 
1   NULL      0.00       NULL  NULL
1   NULL      NULL       0.00  NULL
1   NULL      NULL       NULL  0.00
8   10000.00  NULL       NULL  NULL
8   NULL      100000.00  NULL  NULL
8   NULL      NULL       0.00  NULL
8   NULL      NULL       NULL  10000.00

应该是:

--  --------  ---------  ----  --------
1   10000.00  0.00       0.00  0.00
8   10000.00  100000.00  0.00  10000.00

1 个答案:

答案 0 :(得分:1)

SELECT *
FROM   (SELECT empID,
               coverage,
               CASE planID
                 WHEN 1 THEN 'Basic'
                 WHEN 11 THEN 'Supplemental'
                 WHEN 12 THEN 'Spouse'
                 WHEN 13 THEN 'Dependent'
               END PlanDesc
        FROM   benefitSelected) AS A PIVOT (Sum([coverage]) FOR [PlanDesc] IN ([Basic], [Supplemental], [Spouse], [Dependent])) p 

查询返回:

empID   Basic   Supplemental    Spouse  Dependent
15      100     200             NULL    500
20      100     250             400     NULL