我正在使用 SQL Server 2019。我有一個包含 5 行發票的表格。
--------- ---------
| invoice | amount |
--------- ---------
| ABC | 100 |
| DEF | 125 |
| GHI | 150 |
| JKL | 160 |
| MNO | 170 |
我想回傳獲得最多 235 個運行總數所需的每一行,以及它的一部分。發票 GHI 包含剩余的部分金額 10 (235 - 100 - 125)。
--------- ---------
| invoice | amount |
--------- ---------
| ABC | 100 |
| DEF | 125 |
| GHI | 10 |
--------- ---------
因為這些是唯一的 3 行來獲得請求的 235。我正在考慮類似用戶定義的函式的東西,它回傳一個表,但我似乎無法想出任何可以處理部分運行總數的東西在最后一個。
有什么想法嗎?提前致謝。
uj5u.com熱心網友回復:
好的,所以從您的帖子中我仍然不清楚發票總和背后的原因,但這是我的解決方案。
首先,讓我們創建一個包含 5 個發票行的示例表。
create table dbo.invoices
(
invoice char(10),
amount decimal(10,2)
);
insert into dbo.invoices
values ('ABC', 100), ('DEF', 125), ('GHI', 150), ('JKL', 160), ('MNO', 170);
使用視窗函式,我們可以檢查是否達到了目標金額:
declare @target_amount decimal(10,2) = 235;
with input as (
select invoice
, amount
, running_total = sum(amount) over(order by invoice asc)
, target_amount = @target_amount
from dbo.invoices
), net_amount as (
select *
, net_amount = target_amount - running_total
from input
), selection as (
select *
, new_amount = case when net_amount > 0 then amount else amount net_amount end
, invoice_filter = case when lag(net_amount) over( order by invoice) < 0 then 0 else 1 end
from net_amount
) -- end result
select invoice
, original_amount = amount
, new_amount
from selection
where invoice_filter = 1
結果如下所示:
--------- ----------------- ------------
| invoice | original_amount | new_amount |
--------- ----------------- ------------
| ABC | 100.00 | 100.00 |
| DEF | 125.00 | 125.00 |
| GHI | 150.00 | 10.00 |
--------- ----------------- ------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/332840.html
標籤:查询语句
上一篇:拋出例外:當物體資料模型物件實體化時,C#Windows服務中的“System.IO.FileNotFoundException”
下一篇:添加到DATE小時-TSQL
