在同一选择语句中计算具有不同条件的相同 id 列

Posted

技术标签:

【中文标题】在同一选择语句中计算具有不同条件的相同 id 列【英文标题】:Count same id column with different condition in same select statement 【发布时间】:2014-01-19 20:48:35 【问题描述】:

我需要将两个选择语句合并为一个选择

SELECT count(tbl_employer_post_details.employer_id) pending
  FROM tbl_employer_post_details, 
       tbl_employer_registration
 WHERE job_status=0 
   AND tbl_employer_registration.employer_id = 
                                   tbl_employer_post_details.employer_id
 LIMIT start,max;

第二个查询,唯一的区别是WHERE job_status=1

SELECT count(tbl_employer_post_details.employer_id) approved
  FROM tbl_employer_post_details, 
       tbl_employer_registration
 WHERE job_status=1 
   AND tbl_employer_registration.employer_id = 
                         tbl_employer_post_details.employer_id
  LIMIT start,max;

【问题讨论】:

您是要合并计数(例如,员工总数为 5 人,任何一种状态),还是分开(2 人的工作状态为 0,3 人的工作状态为 1)? 【参考方案1】:
SELECT count(tbl_employer_post_details.employer_id) PostDetails
FROM tbl_employer_post_details, tbl_employer_registration
WHERE job_status IN(0,1) AND  
tbl_employer_registration.employer_id=tbl_employer_post_details.employer_id LIMIT start,max;

SELECT SUM(job_status = 0) pending,
       SUM(job_status = 1) approved
FROM tbl_employer_post_details, tbl_employer_registration
WHERE job_status IN(0,1) AND  
tbl_employer_registration.employer_id=tbl_employer_post_details.employer_id LIMIT start,max;

【讨论】:

我想他想要返回 2 列?【参考方案2】:

这样试试吧。

  SELECT SUM(case when job_status = 0 then 1 else 0 end) pending,
         SUM(case when job_status = 1 then 1 else 0 end) approved
  FROM tbl_employer_post_details d JOIN tbl_employer_registration r
    ON r.employer_id = d.employer_id
 WHERE job_status IN (0, 1)

【讨论】:

【参考方案3】:

试试这个:

SELECT SUM(job_status = 0) pending, SUM(job_status = 1) approved 
FROM tbl_employer_post_details epd 
INNER JOIN tbl_employer_registration er ON epd.employer_id = er.employer_id
WHERE job_status IN (0, 1);

【讨论】:

【参考方案4】:

试试这个方法

SELECT SUM(job_status = 0) pending,
       SUM(job_status = 1) approved
  FROM tbl_employer_post_details d JOIN tbl_employer_registration r
    ON r.employer_id = d.employer_id
 WHERE job_status IN (0, 1)

【讨论】:

以上是关于在同一选择语句中计算具有不同条件的相同 id 列的主要内容,如果未能解决你的问题,请参考以下文章

选择具有不同 where 条件的同一列

如何在具有相同 ID 的列中选择不同的值然后删除它们 PHP SQL Server

如何从其他地方选择具有不同 WHERE 语句的东西

PL/SQL 和条件 FROM 子句

从具有不同条件的同一张表中获取数据[关闭]

如何选择(所有)表 1 中的一行,该行具有与表 2 相同的另一行