簡體   English   中英

SQL聚合具有相同id的行,輔助列中具有特定值

[英]SQL aggregate rows with same id , specific value in secondary column

如果status列中的值之一發生,我想過濾數據庫(PostgreSQL)中的行。 想法是,如果唯一referencestatus僅等於1則對amount列求和。 如果查詢的狀態也為2或與此相關的任何其他status ,則查詢根本不應SELECTreference 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;

Rextester演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM