如何用条件清晰的SQL查询

时间:2017-10-12 16:24:24

标签: sql

简单数据库:

street     | age
1st st     | 2
2nd st     | 3
3rd st     | 4
3rd st     | 2

我想构建一个返回DISTINCT街道名称的查询,但仅适用于那些没有人超过3的家庭。

所以结果将是:

 street        | age
    1st st     | 2
    2nd st     | 3

我该怎么做?我知道DISTINCT,但现在如何为所有与DISTINCT匹配的记录条件化

4 个答案:

答案 0 :(得分:1)

假设表的名称是' tab'。然后你可以尝试:

select distinct street from tab where street not in (select street from tab where age>3);

我创建了一个sql小提琴,您可以在其中查看结果: http://sqlfiddle.com/#!9/2c513d/2

答案 1 :(得分:0)

没有人超过3的家庭的街道名称不同:

SELECT street
FROM table
GROUP BY street
HAVING COUNT(1) <= 3

答案 2 :(得分:0)

USE GROUP BY

Select Street
from yourtable
group by street
Having sum(age)<=3

使用NOT EXISTS

可以实现另一种方式
SELECT *
FROM yourtable a
WHERE NOT EXISTS
    (SELECT street
     FROM yourtable b
     WHERE age > 3
       AND a.street = b.street)

答案 3 :(得分:0)

blockDeviceMapping