簡體   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