MYSQL-同一列上的多个和条件不同的值

时间:2018-10-02 07:16:28

标签: mysql sql select

我有一个表名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    |
+----+------+------+--------+

我的目标是检索具有特定分数的不同用户。例如ssc结果> 4.0和hsc结果> 4.2。

如果我放这样的东西

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

它将返回空值,因为考试不能同时等于'ssc'和'hsc'。如果我这样放置或调节中间状态

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

它将包括用户11,这是意外的,因为我们的目标是过滤ssc中大于4.0的用户。

我的预期输出将是这样

10
12

有什么办法可以做到这一点?

3 个答案:

答案 0 :(得分:4)

您可以尝试在HAVING中使用条件汇总功能,并检查是否都建立了条件。

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);

查询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 |

答案 1 :(得分:1)

使用连接的一种方法

  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

答案 2 :(得分:1)

使用条件聚合进行过滤

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