[英]find sum of n rows values
我需要獲取在價格列中具有特定值的發票號,如果不是所有在價格列中具有該特定值總和值的發票號..如何為此編寫 sql 查詢
我附上了我的表數據的數據
invoice price v1 1000 v2 200 v3 35 v4 500 v5 50 v6 300 v7 400 . . . ' . . vn 34
預期輸出:if(input 500) found =>then found v4
其他((v2,v6)的總和
多連接查詢
select d1.invoice, d1.price, (case when d2.invoice <> d1.invoice then d2.invoice end) as invoice2, (case when d2.invoice <> d1.invoice then d2.price end) as price2 from data d1 left join data d2 on d1.invoice <= d2.invoice where (d1.price = 500 and d2.invoice = d1.invoice) or (d1.price + d2.price) = 500
我當前的查詢沒有給出動態結果,假設輸入是 735,所以結果應該是 3 列 sum of(v2,v3,v4) 的總和,在這種情況下,我必須調整您的查詢。 你能給我建議一種動態的方法嗎?提前致謝。
您可以嘗試以下邏輯,它將返回所有 3 個發票編號 v2、v4 和 v6。
v2 作為價格 = 500
V4 和 v6 的價格總和 = 500
如果要求不同,您可以進行一些更改。 但我這下面的邏輯會幫助你。
SELECT A.invoice
FROM your_table A
CROSS APPLY your_table B
WHERE A.invoice = B.invoice AND A.Price = 500 -- This will check the price as exact input or not
OR (
A.invoice <> B.invoice AND A.Price + B.Price = 500
-- This will check sum of 2 different invoice is same as input or not
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.