如何找到具有相等值的行?
Posted
技术标签:
【中文标题】如何找到具有相等值的行?【英文标题】:How to find row with equal value? 【发布时间】:2020-08-16 13:24:47 【问题描述】:我有一张桌子Accounts
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)。我不知道如何实现这一点(有人可以帮助我吗?
【问题讨论】:
【参考方案1】:使用两个级别的聚合:
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);
我不知道每个客户/分支机构是否可以有多行。如果没有,您只需要:
select client
from t
group by client
having min(amount) = max(amount);
【讨论】:
@Stitch:只是一个建议,虽然窗口函数很好,而且用户的回答也是正确的,在这种情况下,使用上述攻击逻辑远远优于分析逻辑。 @Sujitmohanty30 。 . .我也很困惑为什么 OP 会选择更复杂的方法来解决这个问题。【参考方案2】:您可以使用解析函数来实现相同的功能:
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 ;
【讨论】:
解决方案很好,但我个人的建议是通过@Gordon Linoff 进行侵略。以上是关于如何找到具有相等值的行?的主要内容,如果未能解决你的问题,请参考以下文章