如何找到具有相等值的行?

How to find row with equal value?

我有一个tableAccounts

AMOUNT| ID_CLIENT | ID_BRANCH
  250      1            1
  250      1            3
  100      1            4
  300      2            1
  300      2            3
  450      3            2
  100      3            2
  225      4            1
  225      4            2
  225      4            4
  225      4            5

我需要找到在每个分支中拥有相同金额的客户(例如 ID_CLIENT = 2 和 ID_CLIENT = 4)。我不知道如何实现这个(有人能帮帮我吗?

使用两级聚合:

select client
from (select client, branch, sum(amount) as amount
      from t
      group by client, branch
     ) cb
group by client
having min(amount) = max(amount);

我不知道每个 client/branch 是否可以有多行。如果没有,你只需要:

select client
from t
group by client
having min(amount) = max(amount);

您可以使用分析函数来实现相同的目的:

Demo

with CTE1 as
(
  SELECT A.*, DENSE_RANK() OVER (PARTITION BY ID_CLIENT ORDER BY AMOUNT) DN,
  COUNT(*) OVER (PARTITION BY ID_CLIENT) TOTAL_COUNT
FROM TABLE1 A ORDER BY ID_CLIENT
)
SELECT ID_CLIENT FROM 
(
SELECT ID_CLIENT, SUM(DN), TOTAL_COUNT 
  FROM CTE1 
GROUP BY ID_CLIENT, TOTAL_COUNT 
 HAVING SUM(DN) = TOTAL_COUNT
);

通过使用 First_value 和 Last_value:

Demo

SELECT DISTINCT ID_CLIENT FROM 
(
SELECT A.*, 
FIRST_VALUE(AMOUNT) OVER(PARTITION  BY ID_CLIENT ORDER BY AMOUNT ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FST_VAL,
LAST_VALUE(AMOUNT) OVER(PARTITION  BY ID_CLIENT ORDER BY AMOUNT ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) LST_VAL
FROM TABLE1 A
) X WHERE FST_VAL = LST_VAL ;