在mysql中如何这样打印:仅在一个查询中

时间:2018-08-30 12:32:28

标签: mysql

  

我有一个员工表

enter image description here

  

我想要的是薪水<6000 ,将其转换为一列,   工资> 6000 转换为另一个表...就像这样

enter image description here

  

我尝试这样做:无法产生正确的结果

enter image description here

SELECT 
    (CASE WHEN salary <  6000 THEN salary END) salary_less_then_6000, 
    (CASE WHEN salary >  6000 THEN salary END) salary_gerater_then_6000 
FROM employee

希望您理解我想要的。任何帮助都是可以的

1 个答案:

答案 0 :(得分:1)

实现此目的的方法是创建两个表,一个表的薪水<6000,另一个表的薪水> = 6000,然后JOIN。现在,由于这些表中没有自然顺序,因此我们必须为每个表创建一个人为的行号,然后根据此表JOIN。由于我们不知道哪个表可能有更多行,因此我们必须执行FULL OUTER JOIN。不幸的是,MySQL不支持该功能,因此我们必须使用LEFT JOINUNION来模拟RIGHT JOIN

SELECT e1.salary AS salary_less_then_6000, e2.salary AS salary_greater_then_6000 
FROM (SELECT salary, @rownum1:=@rownum1+1 AS rownum
      FROM employees
      JOIN (SELECT @rownum1 := 0) r
      WHERE salary < 6000
      ORDER BY salary
      ) e1
LEFT JOIN (SELECT salary, @rownum2:=@rownum2+1 AS rownum
      FROM employees
      JOIN (SELECT @rownum2 := 0) r
      WHERE salary >= 6000
      ORDER BY salary
      ) e2
ON e1.rownum = e2.rownum
UNION
SELECT e1.salary AS salary_less_then_6000, e2.salary AS salary_greater_then_6000 
FROM (SELECT salary, @rownum3:=@rownum3+1 AS rownum
      FROM employees
      JOIN (SELECT @rownum3 := 0) r
      WHERE salary < 6000
      ORDER BY salary
      ) e1
RIGHT JOIN (SELECT salary, @rownum4:=@rownum4+1 AS rownum
      FROM employees
      JOIN (SELECT @rownum4 := 0) r
      WHERE salary >= 6000
      ORDER BY salary
      ) e2
ON e1.rownum = e2.rownum

输出(来自我的演示)

salary_less_then_6000   salary_greater_then_6000
3000                    7000
5000                    8000
(null)                  9000

SQLFiddle Demo