获取记录,其中一列具有相同列名的记录范围内的值

时间:2017-04-26 14:45:51

标签: sql postgresql

使用如下表格

+------+-----+------+----------+-----------+
| city | day | hour | car_name | car_count |
+------+-----+------+----------+-----------+
|    1 |  12 |   00 | corolla  |         8 |
|    1 |  12 |   00 | city     |         9 |
|    1 |  12 |   00 | amaze    |         3 |
|    1 |  13 |   00 | corolla  |        17 |
|    1 |  13 |   00 | city     |         2 |
|    1 |  13 |   00 | amaze    |         8 |
|    1 |  14 |   00 | corolla  |         3 |
|    1 |  14 |   00 | amaze    |         1 |
+------+-----+------+----------+-----------+

需要查找city, day, hour所有car_count的{​​{1}}是> = 3且< = 10

预期结果

car_name

3 个答案:

答案 0 :(得分:1)

使用group byhaving

select city,day,hour
from tablename
group by city,day,hour
having sum(case when car_count>=3 and car_count<=10 then 1 else 0 end) = count(*)

答案 1 :(得分:0)

select city, day, hour
from t
group by 1, 2, 3
having bool_and(car_count >= 3)

答案 2 :(得分:0)

条件总和(您的条件)=计数(您的条件) <可以在城市,日和小时分组登记/> 所以基本上我们为每一行创建一个满足条件“10&gt; = car_count&gt; = 3”的标志。现在我们正在计算所有的标志并同时计算它们,如果计数和总和都相等,这意味着你的条件“10&gt; = car_count&gt; = 3”对于所有汽车对抗城市,日和小时都是真的

create table want as
select city,day,hour from have
group by city,day,hour
having sum(car_count>=3 and car_count<=10)=count(car_count>=3 and car_count<=10);

如有任何疑问,请与我联系。