我在试着找出需要多少硬币才能找出零钱,其中一个条件是先给出大硬币.例如10-5-2-1.我知道这个任务可以用循环来解决,但我想知道如何用递归来解决它

有一张桌子:

coin
| id   |  coin  | 
| ---- | ------ |
|  1   |    1   |
|  2   |    2   |
|  3   |    5   |
|  4   |   10   |

即更改=43

43 - 10 = 33   ->   33 - 10 = 23   ->   23 - 10 = 13   ->   13 - 10 = 3   ->   3 can't be decrease by 10 
3 -  can't be decrease by 5 
3 - 2 = 1   ->   1 - can't be decrease by 2
1 - 1 = 0   ->   end

One of example how i try solve this problem

试图获得:

输出:

| id   | count  |  -- how many times coin was used/iterration count 
| ---- | ------ |
|  4   |    4   |
|  3   |    0   |  
|  2   |    1   |
|  1   |    1   |

推荐答案

一种简单的方法是在每次迭代中使用递归CTE减go 较高面额的硬币,直到剩余货币为零.

例如,您可以执行以下操作:

with recursive
p (amount) as (select 43), -- parameter "amount" here
coins (denom) as (select 10 union select 5 union select 2 union select 1),
h (denom, remainder) as ( (
  select c.denom, p.amount - c.denom
  from p
  join coins c on p.amount >= c.denom
  order by c.denom desc limit 1
 ) union all (
  select c.denom, h.remainder - c.denom
  from h
  join coins c on h.remainder >= c.denom
  order by c.denom desc limit 1
  )
)
select * from h;

结果:

 denom  remainder 
 ------ --------- 
 10     33        
 10     23        
 10     13        
 10     3         
 2      1         
 1      0         

请参见db<>fiddle的运行示例.

Sql相关问答推荐

如何查询未命名对象的SON数组

在SQL:2003(PGQ)中,Cypher查询语言、GQL、PGQL和属性图查询的常见子集是什么?'

SQL查询视图与连接?

R中对Arrow duckdb工作流的SQL查询

SQL:如何查找聚合满足条件的连续日期

按分隔符和总和分析字符串

在查询Oracle SQL中创建替代ID

动态组/转置

MS Access问题查询中的自定义字段

基于另一个(SAS、SQL)中的值更新列

Athena 计算从日期到当前时间戳的每月计数

删除对 JSON 数据的未解析引用的 SQL71502 警告

Postgresql - 如何根据阈值计算累积和

通过ID和数据找到每个不同的值

使用长 IN 子句的 SQL 优化

按公司和产品查询最近发票的平均价格的SQL查询

postgres按组消除分区中的NULLS

如何防止 SQL 中的负收入值并将其重新分配到接下来的月份?

查找具有相同连接列数据的所有记录

PostgreSQL 如何在一组项目及其数量上找到完全相同的订单?