【问题标题】: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 放在那里,所以在这种情况下有什么问题?

【问题讨论】:

    标签: sql postgresql greatest-n-per-group


    【解决方案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 。 . .如果这回答了您的问题,您可以接受答案。
    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2015-12-06
    • 2020-04-19
    • 1970-01-01
    • 2022-11-04
    • 2017-04-25
    相关资源
    最近更新 更多