如何从结果中删除重复行

Posted

技术标签:

【中文标题】如何从结果中删除重复行【英文标题】:How to remove duplicate rows from results 【发布时间】:2021-07-03 02:13:01 【问题描述】:

我创建了 SQL 查询

 select 
distinct case when "Date of transaction" >='2021-01-01' and "Date of transaction"<='2021-04-01' then "ClientID" else null END as ClientID, 
"Manager" as Manager,
"RegistrationDate" as RegistrationDate,
"Date of transaction" as DateOfFirstTransaction
from
(SELECT 
distinct uu.id as "ClientID",
uu.email as "Email",
uu.created_at as "RegistrationDate",
initcap(split_part(man.email,'@',1)) as "Manager",
bbt.created_at as "Date of transaction",
bbt.payment as "Amount",
bbt.payment as "Amount, $",
ROW_NUMBER() OVER(PARTITION BY bbt.user_id ORDER BY bbt.created_at) as row_num
from users_user uu 
left join users_user man on uu.account_manager_id=man.id
left join 
(select * from billing_balancetransaction where executed_at is not null and payment>0
and created_at between '2021-01-01' and '2021-04-01'
and  created_at is not null
) bbt on bbt.user_id=uu.id
where 
uu.created_at>='2021-01-01' and uu.created_at<'2021-04-01'
and uu.account_manager_id in (24250,24252,24253)) t
group by 1, row_num, ClientID, Manager, RegistrationDate,DateOfFirstTransaction;

因此,我得到以下数据:

在这种情况下,我只需要先输入每个客户端 ID。这意味着以后的记录应该被删除。因为我已经把 DISTINCT 放在那里,所以在这种情况下有什么问题?

【问题讨论】:

【参考方案1】:

最简单的方法是distinct on。您没有指定如何定义“first”,但假设它是 base don registrationdate:

with t as (
      < your query here >
     )
select distinct on (clientid) t.*
from t
order by clientid, registrationdate;

【讨论】:

@YariyZhlob 。 . .如果这回答了您的问题,您可以接受答案。

以上是关于如何从结果中删除重复行的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 删除CoreData行[重复]

SQL Server中怎样可以从SELECT语句的结果集中删除重复行

如何从 DbVisualizer 中删除表中的重复行

按键从数组中删除行[重复]

如何删除唯一行并保持重复? SQL

如何根据条件表达式从熊猫数据框中删除行[重复]