SQL: - 我正在尝试获取表中的行,其中最多3行应该具有<lt; = 1024

时间:2016-11-27 21:11:54

标签: sql postgresql

这是我的表

   sender     | recipient  | date       | amount
  ------------+------------+------------+--------
   Smith      | Williams   | 2000-01-01 | 200
   Smith      | Taylor     | 2002-09-27 | 1024
   Smith      | Johnson    | 2005-06-26 | 512
   Williams   | Johnson    | 2010-12-17 | 100
   Williams   | Johnson    | 2004-03-22 | 10
   Brown      | Johnson    | 2013-03-20 | 500
   Johnson    | Williams   | 2007-06-02 | 400
   Johnson    | Williams   | 2005-06-26 | 400
   Johnson    | Williams   | 2005-06-26 | 200

查询应该只返回泰勒和约翰逊

因为taylor在一行中有1024个,而johnson在3行(512,100,500 = 1112)中获得它们但不是williams因为它需要四行才能达到1024

我尝试了这个查询:

select   
    q1.r, q1.sum1, q1.c 
from
    (select  
         recipient as r, count(*) as c, sum(amount) as sum1
     from 
         transfers 
     group by 
         recipient) as q1
where 
    c <= 3 AND sum1 <= 1024

4 个答案:

答案 0 :(得分:2)

您可以为每个recipient获取TOP 3金额,然后使用SUMHAVING

WITH Cte AS(
    SELECT *,
        ROW_NUMBER() OVER(PARTITION BY recipient ORDER BY amount DESC) AS rn
    FROM transfers
)
SELECT recipient
FROM Cte
WHERE rn <= 3
GROUP BY recipient
HAVING SUM(amount) >= 1024

答案 1 :(得分:1)

使用Postgresql的LATERAL连接功能:

select a.recipient,sum(c.amount) totamount from
    (select distinct recipient from testtable ) a 
  left join lateral 
    (select amount from testtable where recipient=a.recipient 
     order by amount desc limit 3) c 
  on true group by a.recipient having sum(c.amount) >= 1024 ;

答案 2 :(得分:0)

您可以执行此窗口功能和聚合。

Select recipient
From (select t.*, row_number() over (partition by recipient order by amount desc) as seqnum
      From t
     ) t
Where seqnum <= 3
Group by recipient
Having sum(amount) > 1024

答案 3 :(得分:0)

这些专栏并不完全符合您的要求,但这应该可以满足您的需求

select * from (
select name, 
sum(amount) as total, 
count(*) as rec_count
from transfers 
group by name 
having count(*) <= 3) tbl
where total >= 1024