2

如果出現status列中的某個值,我正在查找數據庫中的行(PostgreSQL)。如果唯一reference只有status等於1,則該想法是對amount列進行求和。如果該查詢的狀態爲2或其他status,則該查詢不應該爲SELECTreferencestatus是指交易狀態。具有相同ID的SQL聚合行,次列中的特定值

當前數據表:

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 

我已經簡化了數據的例子,但我認爲它給了什麼我正在尋找一個好主意。 我只選擇references,但只有狀態爲1,但未成功。 我試過子查詢,使用HAVING子句和其他方法沒有成功。

感謝

+0

嘿你在這個階段的查詢是什麼? – EoinS

回答

2

下面是使用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 
) 
1
SELECT SUM(amount) 
FROM table 
WHERE reference NOT IN (
SELECT reference 
FROM table 
WHERE status<>1 
) 

子查詢選擇所有reference是一個必須被排除在外,則主查詢概括一切,除了他們

1
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 
+1

我喜歡使用'bool_or'聚合函數:) – lad2025

+0

謝謝但是,查詢結果在兩個以上的狀態(即參考文獻2,3)的引用中的答案。導致所有行的聚合。也許我的例子是不夠的,並沒有涵蓋這裏的用例。 – OAK

0

你可以使用windowed functions來算的狀態比1不同OCCURENCES每組:

SELECT SUM(amount) AS amount 
FROM (SELECT *,COUNT(*) FILTER(WHERE status<>1) OVER(PARTITION BY reference) cnt 
     FROM tc) AS sub 
WHERE cnt = 0; 

Rextester Demo

相關問題