在同一选择语句中计算具有不同条件的相同 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 列的主要内容,如果未能解决你的问题,请参考以下文章