wil*_*007 -2 sql sqlite postgresql
我想有一个sql,它给收件人收到的数量> = 1024,转移次数<= 3.
例如,
结果是:
约翰逊上市是因为约翰逊账户上市是因为它在以下三次转账中已收到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
Run Code Online (Sandbox Code Playgroud)
它无法正常工作.我正在使用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')
Run Code Online (Sandbox Code Playgroud)
使用row_number()和派生表来限制每个recipient收到的前三个金额,然后通过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
Run Code Online (Sandbox Code Playgroud)
收益:
+--------------+
| account_name |
+--------------+
| Johnson |
| Taylor |
+--------------+
Run Code Online (Sandbox Code Playgroud)
rextester postgres演示:http://rextester.com/PFR74297
编辑了这个问题,删除了问题第3版的一些相关信息:已经尝试过的内容.
我试试
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.
| 归档时间: |
|
| 查看次数: |
2927 次 |
| 最近记录: |