mysql-multiple and condition在同一列上的不同值上

vkc1a9a2  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(316)

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

我们有办法吗?
yquaqz18

yquaqz181#

使用条件聚合进行筛选

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
kupeojn6

kupeojn62#

一种使用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
lxkprmvk

lxkprmvk3#

您可以尝试在中使用条件聚合函数 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

结果:

| USER |
|------|
|   10 |
|   12 |

相关问题