简体   繁体   中英

Select record only if it contains same column value for all rows

I have a table as below.

样本数据。

I only want job_id if it is rejected by all.

I tried using group by to count the result if it is not rejected by all.

So, I will check if at least one record is as such which is still not rejected.

But it will give me the jobs not rejected by all .

I want job_id of those jobs which is rejected by all .

In the example above It should give record with job_id =2

  const jobRejectedByAll = await MatchedTechnician.findAll({
    where: {
      is_rejected: false,
      job_id: allMatchedJobs,
    },
    group: ['job_id'],
    having: sequelize.literal(`count(job_id) > 1`),
  });

Query:

SELECT job_id
     , 
  FROM matched_technicians AS MatchedTechnician
 WHERE MatchedTechnician.is_rejected = FALSE 
   AND MatchedTechnician.job_id IN (2, 3)
 GROUP 
    BY job_id
 HAVING COUNT(job_id) > 1;

You could use a NOT EXISTS query to check that no value of is_rejected is false :

SELECT DISTINCT job_id
FROM matched_technicians m1
WHERE NOT EXISTS (SELECT * 
                  FROM matched_technicians m2 
                  WHERE m2.job_id = m1.job_id 
                    AND (m2.is_rejected = false
                      OR m2.is_rejected IS NULL)
                  )

Output:

job_id
2

Demo on dbfiddle

An alternate queryway to do this is to count the number of rows for a given job_id and compare it with the number of true values; if they are the same, the job has been rejected:

SELECT job_id
FROM matched_technicians
GROUP BY job_id
HAVING COUNT(*) = SUM(is_rejected)

Demo on dbfiddle

Update

Sequelize version for second approach:

 const jobsRejectedByAllTechs = await MatchedTechnician.findAll({
    group: ['job_id'],
    having: Sequelize.literal('count(*) = SUM(is_rejected)'),
    attributes: ['job_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM