如何获得大于一定数量的数量的总和

时间:2017-03-05 13:37:35

标签: sql postgresql sqlite

我希望有一个sql,它会向收件人收到金额> = 1024,转移次数<= 3。

如,

enter image description here

结果是:

enter image description here

约翰逊自此上市 约翰逊账户上市是因为它在以下三次转账中收到1112美元:512美元+ 100美元+ 500美元,泰勒有1次转账1024美元。威廉姆斯不在那里,因为他在四次交易中收到1200。

我试试

Select recipient as account_name from transfers group by recipient 
having sum(amount)>=1024  and count(amount)<=3

它无法正常工作。 我正在使用PostgreSQL,SQLLites语法也很好。

附件是方便的表格和行创建

 create table transfers (
      sender varchar(1000) not null,
      recipient varchar(1000) not null,
      date date not null,
      amount integer not null
  );

insert into transfers values('Smith','Taylor',convert(date,'2002-09-27'),'1024')
insert into transfers values('Smith','Johnson',convert(date,'2005-06-26'),'512')
insert into transfers values('Williams','Johnson',convert(date,'2010-12-17'),'100')
insert into transfers values('Williams','Johnson',convert(date,'2004-03-22'),'10')
insert into transfers values('Brown','Johnson',convert(date,'2013-03-20'),'500')
insert into transfers values('Johnson','Williams',convert(date,'2007-06-02'),'400')
insert into transfers values('Johnson','Williams',convert(date,'2005-06-26'),'400')
insert into transfers values('Johnson','Williams',convert(date,'2005-06-26'),'200')

3 个答案:

答案 0 :(得分:9)

使用row_number()和派生表将每个recipient限制为收到的前3个金额,然后按recipient分组,返回sum(amount)>=1024

select recipient as account_name
from (
  select * 
    , row_number() over (
        partition by recipient
        order by amount desc
        ) as rn
  from transfers
  ) as i
where rn < 4
group by recipient
having sum(amount)>=1024

返回:

+--------------+
| account_name |
+--------------+
| Johnson      |
| Taylor       |
+--------------+

rextester postgres演示:http://rextester.com/PFR74297

编辑的问题从3rd revision of the question删除了一些相关信息:已经尝试过的内容。

  

我试试

     

Select recipient as account_name from transfers group by recipient
      having sum(amount)>=1024 and count(amount)<=3

     

它无法正常工作。

基于该信息,我得出结论,OP希望找到recipients从任何收件人的转移中收到sum(amount)>=1024 3个或更少的人 - 不仅限于那些转移次数为3或更少的收件人和sum(amount)>=1024

答案 1 :(得分:2)

如果我理解正确你需要这个:

SELECT recipient
  FROM transfers
 GROUP BY 1
HAVING count(*) < 4
   AND sum(amount)>=1024

答案 2 :(得分:0)

使用SQLite的工作解决方案,没有花哨的功能:)

SELECT recipient AS account_name FROM 
    (
        SELECT transfers.recipient, SUM(transfers.amount) AS amountsum FROM transfers
        WHERE transfers.rowid IN (
                                      SELECT tmp.rowid FROM transfers tmp
                                      WHERE transfers.recipient = tmp.recipient
                                      ORDER BY tmp.amount DESC
                                      LIMIT 3
                                  )
        GROUP BY transfers.recipient
    )
WHERE amountsum >= 1024;