【问题标题】:how should I join two queries result on same table?我应该如何在同一张表上加入两个查询结果?
【发布时间】:2018-04-02 09:40:18
【问题描述】:

我有以下两个查询,我有两个连接。

SELECT count(staff_id) FROM employee_kras as e WHERE appraisal_type_id is null
union all
SELECT count(staff_id) from employee_kras as e
where Team_KRA_Status='approved' AND Appraisal_status IS NULL
union all
SELECT count(staff_id) from employee_kras as e where appraisal_status='not submitted' and
    Appraisal_Type_ID IS NOT NULL
union all
SELECT count(staff_id) from employee_kras as e where
    Appraisal_status='submitted' AND Mgr_Rating_id is null

使用以下查询:

SELECT staff_id, 
CASE WHEN appraisal_status='not submitted' and Appraisal_Type_ID IS NOT NULL 
THEN 'Inprogress' 
WHEN  Appraisal_status='submitted' AND Mgr_Rating_id is null 
THEN 'submitted' 
WHEN Team_KRA_Status='approved' AND Appraisal_status IS NULL 
THEN 'approved' 
WHEN appraisal_type_id is null then 'not started' 
ELSE 'submitted' END AS appraisal_status
from employee_kras ORDER BY staff_id;

【问题讨论】:

  • 您的预期输出是什么?这些查询正在做不同的事情。第一个输出聚合计数,第二个输出同一张表中的所有记录。

标签: mysql


【解决方案1】:

您不能加入这些查询。有不同级别的聚合。您可以使用以下查询来获得您正在等待的结果,请注意,我使用静态方法来完成这项工作:

SELECT 'not started' Status , count(staff_id) FROM employee_kras as e WHERE appraisal_type_id is null
union all
SELECT 'approved' Status   , count(staff_id) from employee_kras as e
where Team_KRA_Status='approved' AND Appraisal_status IS NULL
union all
SELECT 'Inprogress' Status , count(staff_id) from employee_kras as e where appraisal_status='not submitted' and
    Appraisal_Type_ID IS NOT NULL
union all
SELECT 'submitted' Status  , count(staff_id) from employee_kras as e where
    Appraisal_status='submitted' AND Mgr_Rating_id is null 

【讨论】:

  • 我无法选择未开始、已批准、正在进行和提交,因为此值会在员工进度后更改
  • 您可以检查您的 seconde 查询中的条件是否与我在 Mine 中输入的条件相同。如果员工进步了,情况也会发生变化。你会得到你期望的结果。但如果有新的 Stats ,则必须在查询中更改它。
  • yaa。非常感谢它正在工作,但它显示列名未启动
  • 我刚刚将查询修改为列名称。我选择了:状态
猜你喜欢
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2018-04-18
相关资源
最近更新 更多