繁体   English   中英

SQL:分组和计数,但仅限于所有记录都大于阈值

[英]SQL: group and count but only if ALL records are greater than a threshold

我在AWS Redshift中有一个带有user_idrecordsmytable 我需要计算每个用户的记录数,但仅限于此用户的所有记录都大于阈值。

mytable中:

user_id | records
------------------
0       | 678
0       | 567
1       | 845
1       | 123
1       | 420
2       | 789

阈值= 400,因此结果应为:

user_id | count
------------------
0       | 2
2       | 1

我将非常感谢你的帮助!

您可以使用group byhaving

select user_id, sum(case when records > 400 then 1 else 0 end) as cnt
from t
group by user_id
having min(records) > 400;

或使用::

select user_id, sum( (records > 400)::int ) as cnt
from t
group by user_id
having min(records) > 400;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM