![](/img/trans.png)
[英]SQL Server : excluding rows from a table IF there is another row with the same col value and a particular secondary column value
[英]SQL aggregate rows with same id , specific value in secondary column
如果status
列中的值之一發生,我想過濾數據庫(PostgreSQL)中的行。 想法是,如果唯一reference
的status
僅等於1
則對amount
列求和。 如果查詢的狀態也為2
或與此相關的任何其他status
,則查詢根本不應SELECT
該reference
。 status
是指交易的狀態。
當前數據表:
reference | amount | status
1 100 1
2 120 1
2 -120 2
3 200 1
3 -200 2
4 450 1
結果:
amount | status
550 1
我簡化了數據示例,但我認為它很好地說明了我要查找的內容。 我僅選擇狀態為1
references
失敗。 我嘗試過使用HAVING
子句和其他方法的子查詢,但HAVING
成功。
謝謝
這是一種使用not exists
的方法來對狀態為1的所有行求和,而其他具有相同引用和非1狀態的行不存在。
select sum(amount) from mytable t1
where status = 1
and not exists (
select 1 from mytable t2
where t2.reference = t1.reference
and t2.status <> 1
)
SELECT SUM(amount)
FROM table
WHERE reference NOT IN (
SELECT reference
FROM table
WHERE status<>1
)
子查詢選擇所有必須排除的reference
s,然后主查詢將除它們之外的所有內容相加
select sum (amount) as amount
from (
select sum(amount) as amount
from t
group by reference
having not bool_or(status <> 1)
) s;
amount
--------
550
您可以使用windowed functions
來計算每個組中狀態發生的次數不等於1的情況:
SELECT SUM(amount) AS amount
FROM (SELECT *,COUNT(*) FILTER(WHERE status<>1) OVER(PARTITION BY reference) cnt
FROM tc) AS sub
WHERE cnt = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.