1

I have a table name results

+----+------+------+--------+
| ID | USER | EXAM | RESULT |
+----+------+------+--------+
|  1 |   10 | ssc  | 4.2    |
|  2 |   10 | hsc  | 4.5    |
|  3 |   11 | ssc  | 4.0    |
|  4 |   11 | hsc  | 4.4    |
|  5 |   12 | ssc  | 5.0    |
|  6 |   12 | hsc  | 5.0    |
|  7 |   13 | ssc  | 3.0    |
|  8 |   13 | hsc  | 3.0    |
+----+------+------+--------+

My goal is to retrieve distinct users having a particular score. For example ssc result > 4.0 and hsc result > 4.2.

If I put something like this

select distinct user from results where 
( exam = 'ssc' and result > 4.0 ) 
and 
( exam = 'hsc' and result > 4.2 ) 

It will return empty as exam cannot equal to 'ssc' and 'hsc' at the same time. If I put or condition in the middle like this

select distinct user from results where 
( exam = 'ssc' and result > 4.0 ) 
or
( exam = 'hsc' and result > 4.2 ) 

It will include user 11 which is unexpected because our target is to filter the users having greater than 4.0 in ssc.

My expected output will be something like this

10
12

Is there any way we can do this?

2
  • what will be your output Commented Oct 2, 2018 at 7:19
  • @ZaynulAbadinTuhin I have added my expected output to the question. Commented Oct 2, 2018 at 7:29

3 Answers 3

4

You can try to use condition aggregate function in HAVING and check both conditions are established.

CREATE TABLE T (
   ID INT,
   `USER` INT,
   EXAM VARCHAR(50),
   RESULT FLOAT
);

INSERT INTO T VALUES (1,10,'ssc', 4.2);
INSERT INTO T VALUES (2,10,'hsc', 4.5);
INSERT INTO T VALUES (3,11,'ssc', 4.0);
INSERT INTO T VALUES (4,11,'hsc', 4.4);
INSERT INTO T VALUES (5,12,'ssc', 5.0);
INSERT INTO T VALUES (6,12,'hsc', 5.0);
INSERT INTO T VALUES (7,13,'ssc', 3.0);
INSERT INTO T VALUES (8,13,'hsc', 3.0);

Query 1:

SELECT USER  
FROM T 
GROUP BY USER 
HAVING 
    SUM(exam = 'ssc' and result > 4.0) = 1 
AND 
    SUM(exam = 'hsc' and result > 4.2) = 1

Results:

| USER |
|------|
|   10 |
|   12 |
Sign up to request clarification or add additional context in comments.

Comments

1

one method using join

  select t1.* from 
(
select * from results where EXAM ='ssc' and RESULT>4.0
    ) t1
  join
(
    select * from  results where EXAM ='hsc' and RESULT>4.2
) as t2 on t1.USER=t2.USER

1 Comment

You solution is also works fine however D-Shih's answer is more clean and small. Thank you anyway :D
1

use conditional aggregation for filter out

select user from tablename
group by user
having 
sum(case when exam='ssc' and result>4.0 then 2 when exam='hsc' and result>4.2 then 1 end)=3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.