I'm creating a small employment site and am wondering if this is possible in MySQL: I have 3 sample jobs and I want to show all users who applied to job_id = 1
who have an application status of 'pending'
while showing the total number of other 'pending'
and 'pending' + 'hired'
applications each user has.
I've been trying to get my head around this but I'm having problems. Is this something MySQL can do?
users
+----+-------+
| ID | name |
+----+-------+
| 1 | hanna |
| 2 | bob |
| 3 | rick |
+----+-------+
job
+--------+------------+
| job_id | jobname |
+--------+------------+
| 1 | 'waiter'|
| 2 | 'janitor'|
| 3 | 'cook'|
+--------+------------+
applications
+----------+---------+-----------+
| user_id | job_id | status |
+----------+---------+-----------+
| 1 | 1 | 'pending' |
| 1 | 2 | 'pending' |
| 1 | 3 | ' hired' |
| 2 | 1 | 'pending' |
| 3 | 1 | 'removed' |
+----------+---------+-----------+
My result set
+--------+---------+-----------+---------------+--------------------+
| job_id | user_id | status | count_pending | count_pendinghired |
+--------+---------+-----------+---------------+--------------------+
| 1 | 1 | 'pending' | 2 | 3 |
| 1 | 2 | 'pending' | 1 | 1 |
+--------+---------+-----------+---------------+--------------------+
The following query comes close to your suggested output. Note that it doesn't make sense to associate a single job_id
with a given user, because a user may have multiple jobs. Likewise, it also doesn't make sense to associate a single status
with a given user, since each record represents an aggregation of more than one status.
SELECT user_id,
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS count_pending,
SUM(CASE WHEN status = 'pending' OR status = 'hired'
THEN 1 ELSE 0 END) AS count_pendinghired
FROM applications
GROUP BY user_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.