Mysql 我将如何解决此查询?
我的表格的简化版本:Mysql 我将如何解决此查询?,mysql,sql,Mysql,Sql,我的表格的简化版本: ------------------------------------------- | sender | recipient | date | amount | ------------------------------------------- | A | B | 2016-01-01 | 500.00 | | C | B | 2016-01-02 | 600.00 | | D |
-------------------------------------------
| sender | recipient | date | amount |
-------------------------------------------
| A | B | 2016-01-01 | 500.00 |
| C | B | 2016-01-02 | 600.00 |
| D | C | 2016-01-03 | 1025.00 |
| D | D | 2016-01-04 | 300.00 |
| D | D | 2016-01-05 | 300.00 |
| D | D | 2016-01-06 | 300.00 |
| D | D | 2016-01-07 | 300.00 |
| D | D | 2016-01-08 | 300.00 |
-------------------------------------------
我如何才能获得一个收件人,他有3行或更少行,合计的最小金额为1024.00或更多
它不需要D,因为它没有超过1024.00的3行
预期结果:
-----------
| recipient |
-----------
| B |
| C |
-----------
这是一个非常简单的查询:
select recipient
from table
group by recipient
having count(*) <= 3 and sum(amount) >= 1024
这很棘手。关键的观察结果是三个最高值之和将超过1024,如果任何3个都超过的话 在MySQL中,您可以使用变量执行此操作:
select recipient, sum(amount) as amount_3
from (select t.*,
(@rn := if(@r = recipient, @rn + 1,
if(@r := recipient, 1, 1)
)
) as rn
from t cross join
(select @r := '', @rn := 0) params
order by recipient, amount desc
) t
where rn <= 3
group by recipient
having sum(amount) >= 1024;
你能给我举个例子吗?但必须有3行求和1024…通过查看您的预期结果,看起来您正在查找少于3行且金额>=1024的收件人…我得到了空结果。。。按计数*>=3且累计金额>=1024的收件人从转账组中选择收件人;count*>=3需要D,应该是因为我想只有3行,假设它的100大于1024。也许我的解释做得不好。。。它不需要是3,它可以是1,1024行或2行加起来超过1024行,最多3行…我需要找到3行或更少行加起来至少1024行或更多行的收件人。得到一个错误,说每个派生表都必须有自己的别名,你能不能help@PrakashPalnati,问一个新问题。@PrakashPalnati,我总是忘记那个愚蠢的限制。。。ANSI SQL没有这样的要求。
select distinct recipient
from tablename t1
where 1024 <= (select sum(amount)
from (select amount
from tablename t2
where t2.recipient = t1.recipient
order by amount desc
limit 3) dt1
) dt2