MySQL return 列中每个值的总计 COUNT 个

MySQL return total COUNT of each value in a column

我有 table 个求职者 三列

JOBSEEKER ID, EMPLOYER ID, HIRING STATUS

每个求职者可以有不同的招聘 每个雇主的状态取决于面试。 现在我想 return 每个总雇用状态的计数 但它应该只计算求职者的 最高招聘状态。

假设约翰是 被雇主评为合格 1 并被雇主雇用 2 约翰只会被算在最高的 他得到的雇用身份是被雇主雇用 2 并且不得计入 QUALIFIED。

HIRED: 1
QUALIFIED: 0
NEAR HIRED: 0
NOT QUALIFIED: 0

这是我的 table

| Jobseeker Id | Employer Id | hstatus_id       |
|--------------|-------------|------------------|
|       1      | 2           | 1(Hired)         |
|       2      | 3           | 1(Hired)         |
|       2      | 4           | 3(Near Hire)     |
|       3      | 4           | 4(Not Qualified) |
|       1      | 2           | 2(Qualified)     |
|       3      | 3           | 1(Hired)         |
|       4      | 2           | 3(Near Hire)     |

而我想要的结果是

| Hiring Status | COUNT |
|---------------|-------|
|     Hired     | 3     |
|   Qualified   | 0     |
|   Near Hire   | 1     |
| Not Qualified | 0     |

谢谢,抱歉英语不好。

您可以为此使用 window 函数:

select hiring_status, sum(seqnum = 1)
from (select js.*,
             row_number() over (partition by Jobseeker_id order by hiring_status desc) as seqnum
      from jobseekers js
     ) js
group by hiring_status;

这假定 hiring_status 是一个数字或以适当数字开头的字符串。

它还假定所有 hiring_status 值都在 jobseekers 中。

编辑:

如果 id 存储在另一个 table 中,那么您只需使用 left join:

select hs.*, count(js.job_seeker)
from hstatus_table hs left join
     (select js.job_seeker, max(hs.hiring_status_id) as max_hiring_status_id
      from jobseekers js
      group by js.job_seeker
     ) js
     on hs.hiring_status_id = max_hiring_status_id
group by hs.hiring_status_id;

您需要 table hStatus_table 的左连接查询 returns 每个 jobseekerid 的最小整数 hiringstatus:

select s.hiringstatus, count(t.jobseekerid) counter
from hStatus_table s
left join (
  select jobseekerid, min(hstatus_id) hstatus_id
  from tablename
  group by jobseekerid
) t on t.hstatus_id = s.id
group by s.id, s.hiringstatus

我假设 table hStatus_table 是这样的:

| ID  | HiringStatus  |
| --- | ------------- |
| 1   | Hired         |
| 2   | Qualified     |
| 3   | Near Hire     |
| 4   | Not Qualified |

参见demo
结果:

| hiringstatus  | counter |
| ------------- | ------- |
| Hired         | 3       |
| Qualified     | 0       |
| Near Hire     | 1       |
| Not Qualified | 0       |