SQL Select - 如何根据字段值显示多个列?

时间:2015-06-29 21:27:21

标签: sql

我一直在尝试整理一个SQL查询,该查询显示每条记录的一行,其中另一个字段的值分解为各自的列。如何为每条记录显示多列和一行?

我有一个表格,其数据类似于以下示例:

+--------------+------------+---------------+
| Employee_Num | Client_Num | Deduction_Num |
+--------------+------------+---------------+
|         1305 |       1000 |             1 |
|         1305 |       1000 |            30 |
|         1312 |       1000 |             1 |
|         1320 |       1000 |             1 |
|         1320 |       1000 |            30 |
|         1323 |       1000 |            30 |
|         1323 |       1000 |             1 |
+--------------+------------+---------------+

我尝试过工会,但结果仍然显示每位员工的多条记录。这是我到目前为止所尝试的内容:

SELECT Employee_Num, Client_Num, Deduction_1, Deduction_30
FROM ( SELECT 
    Employee_Num,
    Client_Num, 
    Deduction_Num AS Deduction_1, 
    Deduction_Num AS Deduction_30
    FROM Employee_Deductions
    WHERE client_num = 1000
    AND Deduction_Num IN (1) 
UNION

    SELECT 
    Employee_Num,
    Client_Num, 
    Deduction_Num AS Deduction_1, 
    Deduction_Num AS Deduction_30
    FROM Employee_Deductions
    WHERE Client_Num, = 1000
    AND Deduction_Num IN (30)  
) AS Datum

WHERE Client_Num = 1000
ORDER BY Employee_Num

我希望这是理想的结果:

+--------------+------------+-------------+--------------+
| Employee_Num | Client_Num | Deduction_1 | Deduction_30 |
+--------------+------------+-------------+--------------+
|         1305 |       1000 |           1 |           30 |
|         1312 |       1000 |           1 |              |
|         1320 |       1000 |           1 |           30 |
|         1323 |       1000 |           1 |           30 |
+--------------+------------+-------------+--------------+

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:1)

从字面上理解你要求的案例陈述可以起作用:

select Employee_Num
  , Client_Num
  , max(case when deduction_num = 1 then deduction_num end) as Deduction_1
  , max(case when deduction_num = 30 then deduction_num end) as Deduction_30
From Employee_Deductions
Group by Employee_Num
  , Client_Num

然而,听起来你想要做的就是根据Technet article来转动数据。希望有所帮助。

答案 1 :(得分:0)

您可以尝试:

SELECT DISTINCT Employee_Num, 
Client_Num, 
CASE WHEN Deduction_Num = 1
     THEN 1
     ELSE ''
     END Deduction_1, 
CASE WHEN Deduction_Num = 30
     THEN 30
     ELSE ''
     END Deduction_30
FROM Employee_Deductions
WHERE Client_Num = 1000
AND Deduction_Num IN (1,30) 

答案 2 :(得分:0)

我建议您通过[self.tabBarController.tabBar setTranslucent:YES]; Employee_Num的组合对结果集进行分组,根据需要计算合成聚合列。 从此中间结果集中,您可以使用所需的输出结构派生表,通过适当地组合计算的聚合来填充列。

示例:

Client_num