在表中添加行最合适的逻辑是啥
Posted
技术标签:
【中文标题】在表中添加行最合适的逻辑是啥【英文标题】:What is the most appropriate logic to add rows in table在表中添加行最合适的逻辑是什么 【发布时间】:2020-12-20 05:39:17 【问题描述】:我有以下表格结构(简化以使基本内容清晰),其中列出了每个贷款类别和银行分行中的前 3 名银行客户。 SNO 列是客户的排名,其值最大为 3。
Loan Category | SNO | Branch | Customer Name | Amount |
---|---|---|---|---|
Home Loan | 1 | abc | Piyush | 10000 |
Home Loan | 2 | abc | Shyam | 5000 |
Home Loan | 3 | abc | Kamal | 2000 |
Home Loan | 1 | xyz | Xman | 50000 |
Home Loan | 2 | xyz | Shyam | 20000 |
Auto Loan | 1 | abc | Birendra | 10000 |
Personal Loan | 1 | xyz | Gyan | 5000 |
Personal Loan | 2 | xyz | Prakash | 2000 |
我正在尝试制作另一个表,如果每个贷款类别和分行中的客户少于 3 个,则为每个分行和类别插入一个虚拟行,其中客户名称和金额的值为 NULL。 本质上,我正在尝试获取下表。
Loan Category | SNO | Branch | Customer Name | Amount | |
---|---|---|---|---|---|
Home Loan | 1 | abc | Piyush | 10000 | |
Home Loan | 2 | abc | Shyam | 5000 | |
Home Loan | 3 | abc | Kamal | 2000 | |
Home Loan | 1 | xyz | Xman | 50000 | |
Home Loan | 2 | xyz | Shyam | 20000 | |
Home Loan | 3 | xyz | added row | ||
Auto Loan | 1 | abc | Birendra | 10000 | |
Auto Loan | 2 | abc | added row | ||
Auto Loan | 3 | abc | added row | ||
Auto Loan | 1 | xyz | added row | ||
Auto Loan | 2 | xyz | added row | ||
Auto Loan | 3 | xyz | added row | ||
Personal Loan | 1 | xyz | Gyan | 5000 | |
Personal Loan | 2 | xyz | Prakash | 2000 | |
Personal Loan | 3 | xyz | added row | ||
Personal Loan | 1 | abc | added row | ||
Personal Loan | 2 | abc | added row | ||
Personal Loan | 3 | abc | added row |
我已经解决了这个问题,方法是使用循环遍历所有类别和分支并插入虚拟行,如果每个类别/分支的 max(sno)
我需要编写一些好的逻辑,最好只使用 SQL 构造或不使用任何循环。
【问题讨论】:
“表结构(简化以使基本的事情清楚),列出了银行每个贷款类别和分行中排名前三的银行客户。” 这本身就是一个有缺陷的设计。每次客户获得新贷款或支付现有贷款时,您都必须不断检查并可能更新该表。更不用说将应计利息应用于贷款余额的影响。您不应该存储可以(并且应该)在运行时计算的内容。 【参考方案1】:好的。所以你必须有一些表,其中branch
和category
在单个或多个表中列出。让我们把它作为你的branch
和category
表,你必须有一些查询产生了问题中提到的结果。让我们称之为your_query
。
您需要为每个类别的每个分支生成 3 条记录。
Select c.category as loan_category,
L.lvl as sno,
B.branch,
Q.cutomername,
Q.amount
From category c
Cross join branch b
Cross Join (select level lvl from dual connect by level <= 3) l
Left Join your_query q on q.branch = c.branch
and q.category = c.category
and l.lvl = q.sno
Ordet by c.category, B.branch, L.lvl
【讨论】:
这正是我想要的。非常感谢。以上是关于在表中添加行最合适的逻辑是啥的主要内容,如果未能解决你的问题,请参考以下文章