SQL 聚合具有相同 id 的行,在辅助列中有特定值
SQL aggregate rows with same id , specific value in secondary column
如果 status
列中的值之一出现,我希望过滤掉数据库 (PostgreSQL) 中的行。如果唯一 reference
只有一个 status
等于 1
,则想法是对 amount
列求和。如果查询的状态也为 2
或任何其他 status
,则该查询根本不应 SELECT
reference
。 status
指的是交易的状态。
当前数据table:
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
子句和其他方法但没有成功。
谢谢
SELECT SUM(amount)
FROM table
WHERE reference NOT IN (
SELECT reference
FROM table
WHERE status<>1
)
子查询选择必须排除的所有 reference
,然后主查询求和除它们之外的所有内容
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;
这是一种使用 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
)
如果 status
列中的值之一出现,我希望过滤掉数据库 (PostgreSQL) 中的行。如果唯一 reference
只有一个 status
等于 1
,则想法是对 amount
列求和。如果查询的状态也为 2
或任何其他 status
,则该查询根本不应 SELECT
reference
。 status
指的是交易的状态。
当前数据table:
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
子句和其他方法但没有成功。
谢谢
SELECT SUM(amount)
FROM table
WHERE reference NOT IN (
SELECT reference
FROM table
WHERE status<>1
)
子查询选择必须排除的所有 reference
,然后主查询求和除它们之外的所有内容
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;
这是一种使用 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
)